python字符串常用方法
1、find(sub[, start[, end]])
在索引start
和end
之間查找字符串sub
找到,則返回最左端的索引值,未找到,則返回-1
start
和end
都可省略,省略start
說明從字符串開頭找
省略end
說明查找到字符串結(jié)尾,全部省略則查找全部字符串
source_str = "There is a string accessing example" print(source_str.find('r')) >>> 3
2、count(sub, start, end)
返回字符串sub
在start
和end
之間出現(xiàn)的次數(shù)
source_str = "There is a string accessing example" print(source_str.count('e')) >>> 5
3、replace(old, new, count)
old
代表需要替換的字符,new
代表將要替代的字符,count
代表替換的次數(shù)(省略則表示全部替換)
source_str = "There is a string accessing example" print(source_str.replace('i', 'I', 1)) >>> There Is a string accessing example # 把小寫的i替換成了大寫的I
4、split(sep, maxsplit)
以sep
為分隔符切片,如果maxsplit
有指定值,則僅分割maxsplit
個(gè)字符串
分割后原來的str類型將轉(zhuǎn)換成list
類型
source_str = "There is a string accessing example" print(source_str.split(' ', 3)) >>> ['There', 'is', 'a', 'string accessing example'] # 這里指定maxsplit=3,代表只分割前3個(gè)
5、startswith(prefix, start, end)
判斷字符串是否是以prefix
開頭,start
和end
代表從哪個(gè)下標(biāo)開始,哪個(gè)下標(biāo)結(jié)束
source_str = "There is a string accessing example" print(source_str.startswith('There', 0, 9)) >>> True
6、endswith(suffix, start, end)
判斷字符串是否以suffix
結(jié)束,如果是返回True
,否則返回False
source_str = "There is a string accessing example" print(source_str.endswith('example')) >>> True
7、lower
將所有大寫字符轉(zhuǎn)換成小寫
8、upper
將所有小寫字符轉(zhuǎn)換成大寫
9、join
將列表拼接成字符串
list1 = ['ab', 'cd', 'ef'] print(" ".join(list1)) >>> ab cd ef
10、切片反轉(zhuǎn)
list2 = "hello" print(list2[::-1]) >>> olleh
到此這篇關(guān)于python字符串常用方法的文章就介紹到這了,更多相關(guān)python字符串內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。