Python 字符串处理常用方法

一字符串的连接join

str={"hello","world","hello","china"}

result=";".join(str)
print(result)
运行结果:world;china;hello

二字符串的截取-切片,split

1切片
str="hello world"
print(str[0:3])
运行结果:hel
2split
str="Bod said:1,2,3,4"
print(str.split(",",2))
运行结果:



三字符串的比较==,!=

str1=1
str2="1"
if str1==str2:
print("相同")
else:
print("不相同")
if str(str1)==str2:
print("相同")
else:
print("不相同")
运行结果:

不相同
相同

2startswith,endwith的用法

word="hello world"
print(word.startswith("hello"))
print(word.endswith("ld",6))
#从索引6~11搜索ld
print(word.endswith("ld",6,len(word)))
运行结果:

四字符串的反转

def reverse(s):
out=""
li=list(s)
for i in range(len(li),0,-1):
out+="".join(li[i-1])
return out
if __name__=="__main__":
print(reverse("hello world,everyone"))
运行结果:

五字符串的查找和替换

1查找find和rfind

sentence="This is a apple"
print(sentence.find("a"))
print(sentence.rfind("a"))
运行结果:

2替换replace

sentence="hello world,hello China"
print(sentence.replace("hello","hi"))
print(sentence.replace("hello","hi",1))
print(sentence.replace("abc","hi"))
运行结果:


六字符串与日期的转换

运行结果:




原文地址:https://www.cnblogs.com/zhuah/p/6979426.html