python字符串find_Python字符串find()
python字符串findPython String find() method is used to find the index of a substring in a string. Python String find()方法用于查找字符串中子字符串的索引。Python字符串find() (Python String find())The syntax of find() func...
python字符串find
Python String find() method is used to find the index of a substring in a string.
Python String find()方法用于查找字符串中子字符串的索引。
Python字符串find() (Python String find())
The syntax of find() function is:
find()函数的语法为:
str.find(sub[, start[, end]])
This function returns the lowest index in the string where substring “sub” is found within the slice s[start:end].
此函数返回在切片 s [start:end]中找到子字符串“ sub”的字符串中的最低索引。
start default value is 0 and it’s an optional argument.
起始默认值为0,它是一个可选参数。
end default value is length of the string, it’s an optional argument.
end默认值是字符串的长度,它是一个可选参数。
If the substring is not found then -1 is returned.
如果未找到子字符串,则返回-1。
We should use the find() method when we want to know the index position of the substring. For checking if a substring is present, we can use in operator.
当我们想知道子字符串的索引位置时,应该使用find()方法。 为了检查是否存在子字符串,我们可以使用in运算符。
Python字符串find()示例 (Python String find() examples)
Let’s look at some simple examples of find() method.
让我们看一下find()方法的一些简单示例。
s = 'abcd1234dcba'
print(s.find('a')) # 0
print(s.find('cd')) # 2
print(s.find('1', 0, 5)) # 4
print(s.find('1', 0, 2)) # -1
Python字符串rfind() (Python String rfind())
Python string rfind() method is similar to find(), except that search is performed from right to left.
Python字符串rfind()方法类似于find(),不同之处在于搜索是从右向左执行的。
s = 'abcd1234dcba'
print(s.rfind('a')) # 11
print(s.rfind('a', 0, 20)) # 11
print(s.rfind('cd')) # 2
print(s.rfind('1', 0, 5)) # 4
print(s.rfind('1', 0, 2)) # -1
查找子字符串的所有索引 (Find all indexes for substring)
Python string find() and rfind() returns the first matched index. We can define a custom function to find all the indexes where the substring is found.
Python字符串find()和rfind()返回第一个匹配的索引。 我们可以定义一个自定义函数,以查找找到子字符串的所有索引。
def find_all_indexes(input_str, search_str):
l1 = []
length = len(input_str)
index = 0
while index < length:
i = input_str.find(search_str, index)
if i == -1:
return l1
l1.append(i)
index = i + 1
return l1
s = 'abaacdaa12aa2'
print(find_all_indexes(s, 'a'))
print(find_all_indexes(s, 'aa'))
Output:
输出:
[0, 2, 3, 6, 7, 10, 11]
[2, 6, 10]
Reference: str.find()
参考: str.find()
python字符串find
更多推荐
所有评论(0)