教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 Python index()方法:检测字符串中是否包含某子串

Python index()方法:检测字符串中是否包含某子串

发布时间:2021-12-12   编辑:jiaochengji.com
教程集为您提供Python index()方法:检测字符串中是否包含某子串等资源,欢迎您收藏本站,我们将为您提供最新的Python index()方法:检测字符串中是否包含某子串资源

同 find() 方法类似,index() 方法也可以用于检索是否包含指定的字符串,不同之处在于,当指定的字符串不存在时,index() 方法会抛出异常。

index() 方法的语法格式如下:

<pre class="brush:html;toolbar:false">str.index(sub[,start[,end]])</pre>

此格式中各参数的含义分别是:

str:表示原字符串;

sub:表示要检索的子字符串;

start:表示检索开始的起始位置,如果不指定,默认从头开始检索;

end:表示检索的结束位置,如果不指定,默认一直检索到结尾。

【例 1】用 index() 方法检索“c.biancheng.net”中首次出现“.”的位置索引。

<pre class="brush:html;toolbar:false">>>> str = "c.biancheng.net" >>> str.index('.') 1</pre>

【例 2】当检索失败时,index()会抛出异常。

<pre class="brush:html;toolbar:false">>>> str = "c.biancheng.net" >>> str.index('z') Traceback (most recent call last):   File "<pyshell#49>", line 1, in <module>     str.index('z') ValueError: substring not found</pre>

<span style="color: rgb(68, 68, 68); font-family: "Helvetica Neue", 微软雅黑, "Microsoft Yahei", Helvetica, Arial, sans-serif; white-space: normal; background-color: rgb(255, 255, 255);">同 find() 和 rfind() 一样,字符串变量还具有 rindex() 方法,其作用和 index() 方法类似,不同之处在于它是从右边开始检索,例如:<pre class="brush:html;toolbar:false">>>> str = "c.biancheng.net" >>> str.rindex('.') 11</pre></span><span style="color: rgb(68, 68, 68); font-family: "Helvetica Neue", 微软雅黑, "Microsoft Yahei", Helvetica, Arial, sans-serif; white-space: normal; background-color: rgb(255, 255, 255);">
</span>

您可能感兴趣的文章:
python中index是什么意思
python index函数是什么意思
Python index()方法:检测字符串中是否包含某子串
Python find()方法:检测字符串中是否包含某子串
python中的find函数怎么用
Python find()方法
python string是什么
Python截取字符串(字符串切片)方法详解
php判断是否包含字符
javascript indexOf方法、lastIndexOf方法的例子

[关闭]
~ ~