Python String index() function returns the lowest index where the specified substring is found. If the substring is not found then ValueError
is raised.
Python String index()函数返回找到指定子字符串的最低索引。 如果未找到子字符串,则引发ValueError
。
Python字符串index()语法 (Python String index() syntax)
This function syntax is:
该函数语法为:
str.index(sub[, start[, end]])
The start parameter default value is 0 and it’s an optional argument.
起始参数的默认值为0,它是一个可选参数。
The end argument default value is length of the string, it’s an optional argument.
end参数的默认值是字符串的长度,它是一个可选参数。
We should use the index() function when we want to know the index position of the substring. For checking if a substring is present, we can use in operator.
当我们想知道子字符串的索引位置时,应该使用index()函数。 为了检查是否存在子字符串,我们可以使用in运算符。
Python字符串索引()与查找() (Python string index() vs find())
Python string index() function raises ValueError if substring is not found whereas find() function returns -1. This is the only difference between these functions.
如果未找到子字符串,Python字符串index()函数将引发ValueError,而find()函数将返回-1。 这是这些功能之间的唯一区别。
Python String index()示例 (Python String index() examples)
Let’s look at some simple examples of index() function.
让我们看一下index()函数的一些简单示例。
s = 'abcd1234dcba'
print(s.index('a'))
print(s.index('cd'))
print(s.index('1', 0, 5))
Output:
输出:
0
2
4
Now let’s look at another example where the substring is not present and ValueError is thrown. I will use a try-except block to catch the exception and print its message.
现在让我们看另一个不存在子字符串并且引发ValueError的示例。 我将使用try-except块来捕获异常并打印其消息。
s = 'abcd1234dcba'
try:
print(s.index('1', 0, 2))
except ValueError as ve:
print(ve)
Output: substring not found
输出: substring not found
Python字符串rindex() (Python String rindex())
Python string rindex() method is similar to index(), except that search is performed from right to left.
Python字符串rindex()方法类似于index(),不同之处在于搜索是从右到左执行的。
s = 'abcd1234dcba'
print(s.rindex('a'))
print(s.rindex('cd'))
print(s.rindex('1', 0, 5))
try:
print(s.rindex('1', 0, 2))
except ValueError as ve:
print(f'Error Message = {ve}')
Output:
输出:
11
2
4
Error Message = substring not found
使用index()查找子字符串的所有索引 (Find all indexes for substring using index())
Python string index() method returns the first matched index. We can define a custom function to find all the indexes where the substring is found.
Python字符串index()方法返回第一个匹配的索引。 我们可以定义一个自定义函数,以查找找到子字符串的所有索引。
def find_all_indexes(input_str, search_str):
l1 = []
length = len(input_str)
position = 0
while position < length:
try:
i = input_str.index(search_str, position)
l1.append(i)
position = i + 1
except ValueError as ve1:
# finally exception will be raised because all the indexes are found
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: Official Documentation
参考: 官方文档