How to Check Characters in a Word in Python

In Python, dealing with strings and characters is an everyday activity and Python provides us with different methods and functionalities to cope with such string-related operations. One of the common operations is to check certain characters present in a word or not and even their frequency. This tutorial is focused on the various methods employed to effectively check characters in a word in Python.

Using the ‘in’ Keyword

The ‘in’ keyword in Python is used as a membership operator and it can check if a particular character occurs in a word. When the character is found in the word, the function returns True and if not, it will return False.

Using the count() method

The count() method in Python is used to get count of how many times a character occurs in a word. If the specific character does not exist in the given word, it returns 0.

Using the find() method

The find() method in Python is used to find the index of a specific character in a word. If the character exists in the word, it will return the index of the first occurrence of the character, and if the character does not exist in the word, it returns -1.

Combining methods

Combining the in, count(), and find() methods, we can create a function that returns whether a character exists in a word, how many times it occurs, and the index of its first occurrence.

The complete code

Output

True
1
0
(True, 1, 0)

Conclusion

The Python programming language provides various simple and sophisticated ways for checking whether a character is in a word. With the use of the ‘in’ keyword, count() method and find() method, we have been able to not only find if a character exists in a word but also to find the frequency of the character and its position in the word. Happy Coding!