Find index of a character in a Python string
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
if __name__ == '__main__': s = "Techie" ch = 'e' index = s.find(ch) if index != -1: print(f"Found character '{ch}' at index {index}") # Found character 'e' at index 1 else: print("Character not found") |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
if __name__ == '__main__': s = "Techie" ch = 'e' try: index = s.index(ch) print(f"Found character '{ch}' at index {index}") # Found character 'e' at index 1 except: print("Character not found") |
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.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = "Techie" ch = 'e' indexes = [i for i, c in enumerate(s) if c == ch] print(f"Found character '{ch}' at index {indexes}") # Found character 'e' at index [1, 5] |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import more_itertools if __name__ == '__main__': s = "Techie" ch = 'e' index = next(more_itertools.locate(s, lambda x: x == ch)) if index != -1: print(f"Found character '{ch}' at index {index}") # Found character 'e' at index 1 else: print("Character not found") |
That’s all about finding the index of a character in a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)