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)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python時(shí)間處理模塊Time和DateTime
這篇文章主要為大家介紹了Python時(shí)間處理模塊Time和DateTime使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
python 讀取txt中每行數(shù)據(jù),并且保存到excel中的實(shí)例
下面小編就為大家分享一篇python 讀取txt中每行數(shù)據(jù),并且保存到excel中的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04
pytorch 指定gpu訓(xùn)練與多gpu并行訓(xùn)練示例
今天小編就為大家分享一篇pytorch 指定gpu訓(xùn)練與多gpu并行訓(xùn)練示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-12-12
使用 Python 的 pprint庫(kù)格式化和輸出列表和字典的方法
pprint是"pretty-print"的縮寫,使用 Python 的標(biāo)準(zhǔn)庫(kù) pprint 模塊,以干凈的格式輸出和顯示列表和字典等對(duì)象,這篇文章主要介紹了如何使用 Python 的 pprint庫(kù)格式化和輸出列表和字典,需要的朋友可以參考下2023-05-05
全網(wǎng)最細(xì) Python 格式化輸出用法講解(推薦)
這篇文章主要介紹了全網(wǎng)最細(xì) Python 格式化輸出用法講解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01

