Python find()方法:检测字符串中是否包含某子串
find() 方法用于检索字符串中是否包含目标字符串,如果包含,则返回第一次出现该字符串的索引;反之,则返回 -1。
find() 方法的语法格式如下:
<pre class="brush:html;toolbar:false">str.find(sub[,start[,end]])</pre>此格式中各参数的含义如下:
str:表示原字符串;
sub:表示要检索的目标字符串;
start:表示开始检索的起始位置。如果不指定,则默认从头开始检索;
end:表示结束检索的结束位置。如果不指定,则默认一直检索到结尾。
【例 1】用 find() 方法检索 “c.biancheng.net” 中首次出现 “.” 的位置索引。
<pre class="brush:html;toolbar:false">>>> str = "c.biancheng.net" >>> str.find('.') 1</pre>【例 2】手动指定起始索引的位置。
<pre class="brush:html;toolbar:false">>>> str = "c.biancheng.net" >>> str.find('.',2) 11</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);">【例 3】手动指定起始索引和结束索引的位置。<pre class="brush:html;toolbar:false">>>> str = "c.biancheng.net" >>> str.find('.',2,-4) -1</pre></span><span style="background-color: rgb(255, 255, 255); color: rgb(68, 68, 68); font-family: "Helvetica Neue", 微软雅黑, "Microsoft Yahei", Helvetica, Arial, sans-serif;">位于索引(2,-4)之间的字符串为“biancheng”,由于其不包含“.”,因此 find() 方法的返回值为 -1。</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);">
注意,Python 还提供了 rfind() 方法,与 find() 方法最大的不同在于,rfind() 是从字符串右边开始检索。例如:
</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);"><pre class="brush:html;toolbar:false">>>> str = "c.biancheng.net" >>> str.rfind('.') 11</pre></span>您可能感兴趣的文章:
python中的find函数怎么用
Python find()方法:检测字符串中是否包含某子串
Python find()方法
Python index()方法:检测字符串中是否包含某子串
python中index是什么意思
python index函数是什么意思
python string是什么
Python中的字符串是什么
Python截取字符串(字符串切片)方法详解
php判断是否包含字符