Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python find first occurrence of character after index

Tags:

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 
like image 355
Gunther Avatar asked Mar 30 '17 16:03

Gunther


People also ask

How do I find the first occurrence of a character in Python?

Use the find() Function to Find First Occurrence in Python We can use the find() function in Python to find the first occurrence of a substring inside a string. The find() function takes the substring as an input parameter and returns the first starting index of the substring inside the main string.

How do you find the index of the first occurrence of character in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you find the first occurrence of an element in a list in Python?

The index() method returns the first occurrence of an element in the list.


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

like image 179
Chris_Rands Avatar answered Oct 06 '22 00:10

Chris_Rands