Python finds first occurrence of character after index

I am trying to get the index of the first occurrence of the character that appears in the string after the specified index. For instance:

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
+4
source share
5 answers

Python is so predictable:

>>> 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.indexaccept what it will be raise ValueErrorwhen a substring is not found instead -1.

+7
source

You can use:

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

.

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
0
for i in range(index, len(string)):
    if string[i] == char:
         print(i)

, index, len(string). , , char, , .

, , , i.

0

Source: https://habr.com/ru/post/1673628/


All Articles