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"))
dswith("ld",6))
#从索引6~11搜索ld
dswith("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" place("hello","hi")) place("hello","hi",1)) place("abc","hi"))
运⾏结果:
六字符串与⽇期的转换
运⾏结果:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论