Python index()方法:检测字符串中是否包含某子串
发布时间:2025-10-17 21:20:41

同 find() 方法类似,index() 该方法还可用于检索是否包含指定的字符串,不同之处在于,当指定的字符串不存在时,index() 方法会抛出异常。
index() 语法格式如下:
str.index(sub[,start[,end]])
该格式中各参数的含义分别为:
str:表示原字符串;
sub:表示要检索的子字符串;
start:如果不指定检索的起始位置,默认从零开始检索;
end:如果不指定检索的结束位置,则默认检索直到结束。
【例 1】用 index() 方法检索“c.biancheng.net第一次出现“”.位置索引。
>>>str="c.biancheng.net"
>>>str.index('.')
1【例 2]检索失败时,index()会抛出异常。
>>>str="c.biancheng.net"
>>>str.index('z')
Traceback(mostrecentcalllast):
File"<pyshell#49>",line1,in<module>
str.index('z')
ValueError:substringnotfound同 find() 和 rfind() 同样,字符串变量也有 rindex() 方法,其作用和 index() 类似的方法不同之处在于它从右边开始检索,例如:>>>str="c.biancheng.net"
>>>str.rindex('.')
11
下一篇 返回列表
