如果有字符串str = 'zi fu chuan chang jian cao zuo' ,一下是常见的操作
一、find
查找字符串str中是否包含字符串‘fu’和字符串'abc',如果包含就返回索引值,如果不包含就返回-1
In [2]: str = 'zi fu chuan chang jian cao zuo'
In [3]: str.find('fu')
Out[3]: 3
In [4]: str.find('abc')
Out[4]: -1
二、index
查找字符串str中是否包含字符串‘fu’和字符串'abc',如果包含就返回索引值,如果不包含会报错:1级索引(ABC)没有找到子串
In [5]: str
Out[5]: 'zi fu chuan chang jian cao zuo'
In [6]: str.index('fu')
Out[6]: 3
In [7]: str.index('abc')
--------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-daba474a0c9f> in <module>()
----> 1 str.index('abc')
ValueError: substring not found
三、count
计算字符串str中出现某个字符的次数(这里为c和b),如果字符串中没有出现返回 "0"
In [10]: str
Out[10]: 'zi fu chuan chang jian cao zuo'
In [11]: str.count('c')
Out[11]: 3
In [12]: str.count('b')
Out[12]: 0
四、replace
替换字符串str中的字符(比如用‘z’替换‘str’中的'c' -全部;用'a'替换'o',从索引开始数替换-1次),可以指定替换几处,默认全部替换
In [15]: str
Out[15]: 'zi fu chuan chang jian cao zuo'
In [16]: str.replace('c','z')
Out[16]: 'zi fu zhuan zhang jian zao zuo'
In [20]: str.replace('o','a',1)
Out[20]: 'zi fu zhuan zhang jian caa zuo'
五、split
以 str 为分隔符切片 ,分隔 出多个子字符串,可以设定最大值
In [24]: str
Out[24]: 'zi fu zhuan zhang jian cao zuo'
In [25]: str.split(' ')
Out[25]: ['zi', 'fu', 'zhuan', 'zhang', 'jian', 'cao', 'zuo']
In [26]: str.split(' ',2)
Out[26]: ['zi', 'fu', 'zhuan zhang jian cao zuo']
In [27]: str
Out[27]: 'zi fu zhuan zhang jian cao zuo'
六、startswith
检查字符串是否是以'z'开头,如果是,返回''True'',不是就返回''False''
In [29]: str
Out[29]: 'zi fu zhuan zhang jian cao zuo'
In [30]: str.startswith('z')
Out[30]: True
In [31]: str.startswith('i')
Out[31]: False
七、endswith
和startswith相反,检查字符串是否是以‘o’结尾,是就返回True ,不是就返回False
In [32]: str
Out[32]: 'zi fu zhuan zhang jian cao zuo'
In [33]: str.endswith('o')
Out[33]: True
八、lstrip
删除字符串''str'' 左边的空白字符,不改变原文件
In [35]: str = " zi fu zhuan zhang jian cao zuo "
In [36]: str
Out[36]: ' zi fu zhuan zhang jian cao zuo '
In [37]: str.lstrip()
Out[37]: 'zi fu zhuan zhang jian cao zuo '
九、rstrip
删除字符串''str'' 末尾的空白字符,不改变原文件
In [39]: str
Out[39]: ' zi fu zhuan zhang jian cao zuo '
In [40]: str.rstrip()
Out[40]: ' zi fu zhuan zhang jian cao zuo'
In [41]: str
Out[41]: ' zi fu zhuan zhang jian cao zuo '
十、strip
删除字符串''str''两端的空白字符,不改变原文件
In [42]: str
Out[42]: ' zi fu zhuan zhang jian cao zuo '
In [43]: str.strip()
Out[43]: 'zi fu zhuan zhang jian cao zuo'
In [44]: str
Out[44]: ' zi fu zhuan zhang jian cao zuo '
十一、isdigit
检查字符串''str''中是否只包含数字,如果只包含数字则返回 True 否则返回 False.
In [47]: str1 = '123456788'
In [48]: str2 = '12345cigig'
In [49]: str1.isdigit()
Out[49]: True
In [50]: str2.isdigit()
Out[50]: False
十二、join
将一个字符串(str1、str3)当作一个字符插入到另一个字符串中的每一个字符后,造出一个新的字符串,不改变原文件
In [54]: str1 = '1111111111'
In [55]: str2 = '2222222222'
In [56]: str1.join(str2)
Out[56]: '2111111111121111111111211111111112111111111121111111111211111111112111111111121111111111211111111112'
In [57]: str3 = 0
In [59]: str3 = '0'
In [60]: str3.join(str1)
Out[60]: '1010101010101010101'