python 自带的两个查找字符串的方法:find 和rfind.
Python String find() Method
Description:
This method determines if
Syntax:
str.find(str, beg=0 end=len(string)) |
Parameters:
Here is the detail of parameters:
-
str: specifies the string to be searched.
-
start
: starting index, by default its 0 -
end
: ending index, by default its equal to the lenght of the string.
Return Value:
It returns index if found and -1 otherwise.输出的index从0开始,和list是一致的,index都是从0开始
Example:
#!/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); |
This will produce following result:
15 15 -1 |
find 是从左起始查找,对应的从右开始查找的方法是rfind() Method |
Description:
This method returns the last index where the substring
Syntax:
str.rfind(str, beg=0 end=len(string)) |
Parameters:
Here is the detail of parameters:
-
str: specifies the string to be searched.
-
start
: starting index, by default its 0 -
end
: ending index, by default its equal to the lenght of the string.
Return Value:
It returns last index if found and -1 otherwise.
Example:
#!/usr/bin/python str = "this is really a string example....wow!!!"; str = "is"; print str.rfind(str); print str.rfind(str, 0, 10); print str.rfind(str, 10, 0); print str.find(str); print str.find(str, 0, 10); print str.find(str, 10, 0); |
This will produce following result:
5 5 -1 2 2 -1 |