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 |
本文详细介绍了Python中用于字符串搜索的方法find和rfind。find方法用于从左向右搜索子字符串并返回其首次出现的位置,而rfind则用于从右向左进行搜索。文章通过实例展示了如何使用这两个方法,并解释了它们的参数设置。
650

被折叠的 条评论
为什么被折叠?



