字符串方法find/rfind/rindex/index/count/replace

本文详细介绍了Python字符串的find、rfind、rindex、index、count和replace方法。find和rfind用于查找子串在字符串中的位置,index和rindex在找不到时会抛出错误,count用于统计子串出现的次数,而replace则用于替换指定子串,可限制替换次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用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

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值