This post will discuss how to find the index of the first occurrence of a character in a string in Python.

1. Using find() function

The standard solution to find a character’s position in a string is using the find() function. It returns the index of the first occurrence in the string, where the character is found. It returns -1 when the character is not found.

Download  Run Code

2. Using index() function

Alternatively, you can use the index() function, which is similar to the find() function, but raises ValueError when the character is not found.

Download  Run Code

3. Using enumerate() function

Here’s solution using enumerate() function with generators. This is useful when you need to find the position of all characters in a string that satisfy a condition.

Download  Run Code

4. Using more_itertools.locate() function

Finally, you can use the locate() function from the more_itertools Python module to search for characters in a string. It yields each character’s index in the string for which the specified predicate returns True.

Download Code

That’s all about finding the index of a character in a string in Python.