Python查找索引后第一个出现的字符

Python查找索引后第一个出现的字符,python,Python,我试图获取字符串中在指定索引之后出现的第一个字符的索引。例如: string = 'This + is + a + string' # The 'i' in 'is' is at the 7th index, find the next occurrence of '+' string.find_after_index(7, '+') # Return 10, the index of the next '+' character >>> 10 Python是如此可预测:

我试图获取字符串中在指定索引之后出现的第一个字符的索引。例如:

string = 'This + is + a + string'

# The 'i' in 'is' is at the 7th index, find the next occurrence of '+'
string.find_after_index(7, '+')

# Return 10, the index of the next '+' character
>>> 10

Python是如此可预测:

>>> string = 'This + is + a + string'
>>> string.find('+',7)
10
签出
帮助(str.find)

也适用于
str.index
,但当未找到子字符串时,这将
引发ValueError
而不是
-1

您可以使用:

start_index = 7
next_index = string.index('+', start_index)
阅读

上述代码将从您提供的索引
index
循环到字符串的长度
len(string)
。然后,如果字符串的索引等于您要查找的字符,
char
,则它将打印索引


您可以将其放入一个函数中,然后传入、字符串、索引和字符,然后返回i。

请参阅:为什么要这样做,而不是将
start\u index
传递到
index()
?因为我的Python已经生锈了:)根据您的建议对其进行了更新。请注意,
list.index
的语法也非常类似,尽管直到最近才有文档记录,但读了这篇文章后我流下了眼泪。蟒蛇很漂亮。我不知道这个发现需要更多的论证。
start_index = 7
next_index = string.index('+', start_index)
string.find('+', 7)
In [1]: str.index?
Docstring:
S.index(sub[, start[, end]]) -> int

Like S.find() but raise ValueError when the substring is not found.
Type:      method_descriptor

In [2]: string = 'This + is + a + string'

In [3]: string.index('+', 7)
Out[3]: 10
for i in range(index, len(string)):
    if string[i] == char:
         print(i)