一.檢測(cè) str 是否包含在 mystr中幅垮,如果是返回開(kāi)始的索引值耿导,否則返回-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),如果字符串中沒(méi)有出現(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',從索引開(kāi)始數(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'開(kāi)頭,如果是鲤孵,返回''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'