python字符串

一.檢測(cè) str 是否包含在 mystr中,如果是返回開始的索引值,否則返回-1

In [1]: str = 'hello wo shi yang ya ming'
In [2]: str
Out[2]: 'hello wo shi yang ya ming'
In [3]: str.index('wo')
Out[3]: 6
In [4]: str.index('hjk')

二、count
計(jì)算字符串str中出現(xiàn)某個(gè)字符的次數(shù)(這里為c和b),如果字符串中沒有出現(xiàn)返回 "0"

In [7]: str
Out[7]: 'hello wo shi zi fu chuan jiu shi wo'
In [8]: str.count('a')
Out[8]: 1
In [9]: str.count('b')
Out[9]: 0

三、replace
替換字符串str中的字符(比如用‘z’替換‘str’中的'c' -全部;用'a'替換'o',從索引開始數(shù)替換-1次),可以指定替換幾處,默認(rèn)全部替換

In [10]: str
Out[10]: 'hello wo shi zi fu chuan jiu shi wo'
In [11]: str.replace('d','b')
Out[11]: 'hello wo shi zi fu chuan jiu shi wo'
In [12]: 'hello wo shi zi fu chuan jiu shi wo'
Out[12]: 'hello wo shi zi fu chuan jiu shi wo'
In [15]: str.replace('o','a',1)
Out[15]: 'hella wo shi zi fu chuan jiu shi wo'

四、split
以 str 為分隔符切片 ,分隔 出多個(gè)子字符串,可以設(shè)定最大值

In [16]: str
Out[16]: 'hello wo shi zi fu chuan jiu shi wo'
In [17]: str.split(' ')
Out[17]: ['hello', 'wo', 'shi', 'zi', 'fu', 'chuan', 'jiu', 'shi', 'wo']
In [18]: str.split(' ',2)
Out[18]: ['hello', 'wo', 'shi zi fu chuan jiu shi wo']
In [19]: ['wo', 'shi', 'zi' 'fu']
Out[19]: ['wo', 'shi', 'zifu']
In [20]: str
Out[20]: 'hello wo shi zi fu chuan jiu shi wo'

五、startswith
檢查字符串是否是以'z'開頭,如果是,返回''True'',不是就返回''False''

In [20]: str
Out[20]: 'hello wo shi zi fu chuan jiu shi wo'
In [21]: str
Out[21]: 'hello wo shi zi fu chuan jiu shi wo'
In [22]: str.startswith('z')
Out[22]: False
In [23]: str.startswith('i')
Out[23]: False

六、endswith
和startswith相反,檢查字符串是否是以‘o’結(jié)尾,是就返回True ,不是就返回False

In [24]: str
Out[24]: 'hello wo shi zi fu chuan jiu shi wo'
In [25]: str.endswith('o')

七、lstrip
刪除字符串''str'' 左邊的空白字符,不改變?cè)募?/p>

In [32]: str
Out[32]: '      zi fu zhuan zhang jian cao zuo      '
In [33]: ' str zhun zhang jian cao zuo    '
Out[33]: ' str zhun zhang jian cao zuo    '
In [34]: str.lstrip()
Out[34]: 'zi fu zhuan zhang jian cao zuo      '

八、strip
刪除字符串''str''兩端的空白
字符,不改變?cè)募蘒n [38]:

str
Out[38]: '      zi fu zhuan zhang jian cao zuo      '
In [39]: str.strip()
Out[39]: 'zi fu zhuan zhang jian cao zuo'
In [40]: str
Out[40]: '      zi fu zhuan zhang jian cao zuo      '

九、isdigit
檢查字符串''str''中是否只包含數(shù)字,如果只包含數(shù)字則返回 True 否則返回 False.

In [41]: str1 = '123123'
In [42]: str2 = '2222121'
In [43]: str1.isdigit()
Out[43]: True

十、join
將一個(gè)字符串(str1、str3)當(dāng)作一個(gè)字符插入到另一個(gè)字符串中的每一個(gè)字符后,造出一個(gè)新的字符串,不改變?cè)募?/p>

In [52]: str1 = '11111'
In [53]: str2 = '222222'
In [54]: str1.join(str2)
Out[54]: '2111112111112111112111112111112'
In [55]: str = 0
In [56]: str = '0'
In [57]: str3.join(str1)
Out[57]: '101010101'
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容