Python3 常用字符串操作


生成字符串

.join()方法生成字符串 

 1 list1 = ['abc', 'DEF', 123]
 2 list2 = [str(i) for i in list1] 3 # 使用列表推導式,把列表中元素統一轉化為str類型 4 list3 = ' ' .join(list2) 5 # 把列表中的元素用空格隔開,用.join()方法將序列中的元素以指定的字符連接生成一個新的字符串。 6 print(type(list1), list1) 7 print(type(list2), list2) 8 print(type(list3), list3) 9 # 輸出結果 10 # <class 'list'> ['abc', 'DEF', 123] 11 # <class 'list'> ['abc', 'DEF', '123'] 12 # <class 'str'> abc DEF 123

 很多地方很多時候生成了元組、列表、字典后,可以用 join() 來轉化為字符串。

清理字符串

1. strip()方法:

1 str1 = ' a b c d e '
2 print(str1.strip())
3 
4 # 'a b c d e'

>> 移除字符串首尾指定的字符(默認為空格或換行符)或字符序列。

>> .lstrip() 和 .rstrip() 方法分別指定截取左邊或右邊的字符

1 str2 = "     this is string example....wow!!!     "
2 print(str2.lstrip())
3 str3 = "88888888this is string example....wow!!!8888888"
4 print(str3.rstrip('8'))
5 
6 # this is string example....wow!!!     
7 # 88888888this is string example....wow!!!

 

2. replace()方法:

該方法主要用於字符串的替換replace(old, new, max)

>>返回字符串中的 old(舊字符串) 替換成 new (新字符串)后生成的新字符串,如果指定第三個參數 max,則替換不超過 max 次。

1 str1 = " a b c d e "
2 print(str1 .replace(" ", ""))
3 
4 # 'abcde'

 

3. join()+split()方法:

1 str1 = ' a b c d e '
2 "".join(str1.split(' '))
3 
4 # abcde

 

字符串內容統計

.count()方法

參數(str, beg= 0,end=len(string))

返回 str 在 string 里面出現的次數,如果 beg 或者 end 指定則返回指定范圍內 str 出現的次數

str="www.runoob.com"
sub='o'
print ("str.count('o') : ", str.count(sub))

sub='run'
print ("str.count('run', 0, 10) : ", str.count(sub,0,10))

# str.count('o') : 3
# str.count('run', 0 10) : 1

 

字符串切分

.split()方法

參數(str="", num=string.count(str))

num=string.count(str)) 以 str 為分隔符截取字符串,如果 num 有指定值,則僅截取 num+1 個子字符串。返回分割后的字符串列表。

str = "this is string example....wow!!!"
print (str.split( ))       # 以空格為分隔符
print (str.split('i',1))   # 以 i 為分隔符
print (str.split('w'))     # 以 w 為分隔符

# ['this', 'is', 'string', 'example....wow!!!']
# ['th', 's is string example....wow!!!']
# ['this is string example....', 'o', '!!!']

 


免責聲明!

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



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