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
個字符串
分割后原來的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個
5、startswith(prefix, start, end)
判斷字符串是否是以prefix
開頭,start
和end
代表從哪個下標開始,哪個下標結(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python遠程開發(fā)環(huán)境部署與調(diào)試過程圖解
這篇文章主要介紹了Python遠程開發(fā)環(huán)境部署與調(diào)試過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12Python一鍵查找iOS項目中未使用的圖片、音頻、視頻資源
這篇文章主要介紹了Python-一鍵查找iOS項目中未使用的圖片、音頻、視頻資源,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2019-08-08opencv python 圖片讀取與顯示圖片窗口未響應問題的解決
這篇文章主要介紹了opencv python 圖片讀取與顯示圖片窗口未響應問題的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04Python3 pip3 list 出現(xiàn) DEPRECATION 警告的解決方法
今天小編就為大家分享一篇Python3 pip3 list 出現(xiàn) DEPRECATION 警告的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02