Python find first occurrence of character after index

Question:

I am trying to get the index of the first occurrence of a character that occurs in a string after a 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
Asked By: Gunther

||

Answers:

Python is so predicable:

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

Checkout 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.

Answered By: Chris_Rands

You can use:

start_index = 7
next_index = string.index('+', start_index)
Answered By: Engineero
string.find('+', 7)

Read the documentation.

Answered By: Sangbok Lee
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
Answered By: 宏杰李
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.

You could put this in a function and pass in the, string, index and character and then return i.

Answered By: Jonathan Bartlett
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.