Python在索引后找到第一次出现的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43123177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python find first occurrence of character after index
提问by Gunther
I am trying to get the index of the first occurrence of a character that occurs in a string aftera specified index. For example:
我正在尝试获取在指定索引之后出现在字符串中的字符第一次出现的索引。例如:
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
回答by Chris_Rands
Python is so predicable:
Python是如此可预测:
>>> string = 'This + is + a + string'
>>> string.find('+',7)
10
Checkout help(str.find)
:
结帐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.
Also works with str.index
except that this will raise ValueError
instead of -1
when the substring is not found.
也适用,str.index
除了这将raise ValueError
代替-1
未找到子字符串时。
回答by Engineero
You can use:
您可以使用:
start_index = 7
next_index = string.index('+', start_index)
回答by Sangbok Lee
回答by u6856342
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
回答by Jonathan Bartlett
for i in range(index, len(string)):
if string[i] == char:
print(i)
The above code will loop through from the index you provide index
to the length of the string len(string)
. Then if the index of the string is equal to the character, char
, that you are looking for then it will print the index.
上面的代码将从您提供的索引循环到index
字符串的长度len(string)
。然后,如果字符串的索引等于char
您要查找的字符 ,则它将打印索引。
You could put this in a function and pass in the, string, index and character and then return i.
你可以把它放在一个函数中并传入字符串、索引和字符,然后返回 i。