find函数

Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

str.find(str,beg=0,end=len(string))

  • str -- 指定检索的字符串
  • beg -- 开始索引,默认为0。
  • end -- 结束索引,默认为字符串的长度。
>>> str = 'this is a big dream'
>>> str.find(a)                            #a不是字符串,注意!!!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> str.find('a')
8
>>> str.find('big')
10
>>> str.find('c')
-1
>>> 
#!/usr/bin/python

str1 = "this is string example....wow!!!";
str2 = "exam";

print str1.find(str2);
print str1.find(str2, 10);
print str1.find(str2, 40);


15
15
-1
>>> a = 'this is a big dream'
>>> a.find('big')
10
>>> a.find('bb')
-1

1.find返回的是big这个字符串第一个字符b的位置,而不是整个字符串或字符串某个其他字符的位置。

2.只有整个字符串满足都在大的字符串里面时,才会返回位置。即使第一个字符或者其他字符在大的字符串里也不行。

原文地址:https://www.cnblogs.com/ymjyqsx/p/6249205.html