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"))
運行結果:

 

 
        

六字符串與日期的轉換

運行結果:

 

 

 
        



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM