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

时间:2017-03-30 16:14:30

标签: 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

5 个答案:

答案 0 :(得分:15)

Python是如此可预测:

>>> string = 'This + is + a + string'
>>> string.find('+',7)
10

结帐help(str.find)

find(...)
    S.find(sub[, start[, end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

同样适用于str.index,但在找不到子字符串时,raise ValueError代替-1

答案 1 :(得分:0)

您可以使用:

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

答案 2 :(得分:0)

string.find('+', 7)

阅读the documentation

答案 3 :(得分:0)

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

答案 4 :(得分:0)

nullglob

上面的代码将从您提供的索引for i in range(index, len(string)): if string[i] == char: print(i) 循环到字符串index的长度。然后,如果字符串的索引等于您要查找的字符len(string),那么它将打印索引。

你可以将它放在一个函数中并传入,字符串,索引和字符,然后返回i。