用dir(str)可以查询字符串的所有方法
1.find
语法:str.find(sub, [start,end) ) \\\\\根据指定的数据查找对应的索引
解释:在字符串中查找子串,如果找到,返回子串的第一个字符的index,否则返回 -1。
note1:可以指定搜索的范围,[start,end),find方法返回的不是布尔值,找到返回index,找不到返回-1。
note2:如果在这个字符串中存在多个很多个sub,则返回第一个sub的第一个字符的index。
>>> x = 'with a moo-moo here, and a moo-moo there'
>>> x.count('moo')
4
>>> x.find('moo')
7
>>> x.find('with')
0
>>> x.find('happy')
-1
>>> x.find('moo',11,17)
11
1.1 rfind
语法:str.rfind(sub,[start,end)) \\\\\根据指定的数据查找对应的索引
解释:返回找到的最后一个子串的第一个字符的索引,没有找到就返回-1,可以提供范围。
>>> x = 'with a moo-moo here, and a moo-moo there'
>>> x.rfind('moo')
31
>>> x.rfind('happy')
-1
>>> x.rfind('moo',1,20)
11
2.index
语法:str.index(sub, [start,end) ) \\\\\根据指定的数据查找对应的索引
解释:在字符串中查找sub子串,如果找到,返回子串的第一个字符的index,否则会ValueError。
>>> x = 'with a moo-moo here, and a moo-moo there'
>>> x.index('moo')
7
>>> x.index('moo',11,17)
11
>>> x.index('like')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
2.2 rindex
语法:str.rindex(sub,[start,end)) \\\\\根据指定的数据查找对应的索引
解释:返回找到的最后一个子串的第一个字符的索引,没有会引发ValueError,可以提供范围。
>>> x = 'with a moo-moo here, and a moo-moo there'
>>> x.rindex('moo')
31
>>> x.rindex('happy')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> x.rindex('moo',1,20)
11
3.count
语法:str.count(sub,[start,end)) \\\\\\统计字符串某个字符出现的字数
解释:计算sub在字符串中出现的次数,没有出现返回0;
>>> x = 'with a moo-moo here, and a moo-moo there'
>>> x.count('like')
0
>>> x.count('moo')
4
>>> x.count('moo',7,14)
2
4.replace
语法:str.replace(old,new,[max])
解释:将str中old,替换成new,max为替换次数,返回替换后的结果,但为暂时性替换;
note:max为可选参数,省略不写则为替换字符串中所有的old,若指定max,则替换次数不超过max次,若max>len(old),则new
替换所有的old。
>>> x = 'with a moo-moo here, and a moo-moo there'
>>> x.replace('moo','like')
'with a like-like here, and a like-like there'
>>> x = 'with a moo-moo here, and a moo-moo there'
>>> x.replace('moo','like',2)
'with a like-like here, and a moo-moo there'
>>> x.replace('like','look')
'with a moo-moo here, and a moo-moo there'
>>> x = 'with a moo-moo here, and a moo-moo there'
>>> x.replace('moo','like')
'with a like-like here, and a like-like there'
>>> print(x)
with a moo-moo here, and a moo-moo there