字符串的函数操作
1、find:检查str是否包含在mystr(字符串)中,如果是返回开始的索引值,否则返回0
mystr.find(str,start=0,end=len(mystr))
end 值可以小于等于len(mystr)
python交互模式下
>>> a
'abcdef'
>>> b
'abc'
>>> a.find(b,0,5)
0
>>> a.find(b,1,3)
-1
2、index:与find() 方法相同,只不过如果str不在mystr中会报告异常
mystr.index(str,start=0,end=len(mystr))
>>> a
'hello world'
>>> b
'he'
>>> a.index(b,0,5)
0
>>> a.index(b,0,2)
0
>>> a.index(b,0,1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
(substring not found 字符串未找到
find和index中的范围都为 左闭右开区间 0–length)
3、count:返回str在start和end之间在mystr里面出现的次数
mystr.count(str,start=0,end=len(mystr))
>>> a
'hello world'
>>> a.count('l',0,10)
3
4、replace:把mystr中的str1替换为str2,如果count指定,则替换不超过count次
mystr.replace(str1,str2,mystr(count(str1))
>>> a
'hello world'
>>> a.replace('l','L')
'heLLo worLd'
5、split:以str 为分割符切片mystr,如果maxsplit有指定值,则仅分割maxsplit个子字符串
mystr.split(str=" ",2)
>>> a
'hello world'
>>> a.split(' ',2)
['hello', 'world']
6、capitalize:把字符串的第一个字符大写
mystr.capitalize()
>>> a
'hello world'
>>> a.capitalize()
'Hello world'
7、title:把字符串的每个单词首字母大写
mystr.title()
>>> a
'hello world'
>>> a.title()
'Hello World'
8、startswith:检查字符串开头是否以str开头,是则返回True,否则返回False
mystr.startswith(str)
>>> a
'hello world'
>>> a.startswith('s')
False
>>> a.startswith('h')
True
9、endswith:检查字符串是否以str结束,是返回True,否返回False
mystr.endswith(str)
10、lower:转换mystr中的大写字符为小写
mystr.lower()
11、upper:转换mystr中的小写字符为大写
mystr.upper()
>>> a
'hello world'
>>> a.upper()
'HELLO WORLD'
12、ljust:返回一个原字符串左对齐,并使用空格填充至长度 X 的新字符串
mystr.ljust(X)
13、rjust:返回一个原字符串右对齐,并使用空格填充至长度 X 的新字符串
mystr.rjust(X)
>>> a
'hahaha'
>>> a.rjust(10)
' hahaha'
14、center:返回一个原字符串居中,并使用空格填充长度至 X 的新字符
mystr.center(X)
>>> a
'hello kugou'
>>> a.center(16)
' hello kugou '
15、lstrip:删除mystr左边的空白字符
16、rstrip:删除字符串末尾的空白
17、strip:删除字符串两端的空白字符
mystr.lstrip()、mystr.rstrip()、mystr.strip()
>>> a
' hello kugou'
>>> a.lstrip()
'hello kugou'
18、rfind:类似于find() 函数,但是是从右边开始寻找
19、rindex:类似于index() 函数,也是从右边开始寻找
20、partition:把mystr以str 分割成三部分,str前 str str后
mystr.partition(str)
21、rpartition:类似于partition()函数,不过是从右边开始
>>> a='abc'
>>>> a.partition('b')
('a', 'b', 'c')
22、splitlines:按照行分隔,返回一个包含各行作为元素的列表
mystr.splitlines()
23、isalpha:如果mystr 所有字符都是字母 则反回 True,否则返回False
mystr.isalpha()
24、isdigit:如果mystr 只包含数字则返回True,否则返回False
mystr.isdigit()
25、isalnum:如果 mystr 所有字符都是字母或数字返回True,否则返回False
mystr.isalnum()
26、isspace:如果 mystr 中只包含空格,则返回True ,否则返回Fales
mystr.isspace()
27、join:mystr 中每个字符后面插入str ,构造出一个新的字符串(str中最后一个字符后不添加mystr)
mystr.join(str)
>>> a
'hello world '
>>> b
'123'
>>> a.join(b)
'1hello world 2hello world 3'