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.
1 2 3 4 |
#Python code char = 'a' word = 'apple' print(char in word) |
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.
1 2 3 4 |
#Python code char = 'a' word = 'apple' print(word.count(char)) |
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.
1 2 3 4 |
#Python code char = 'a' word = 'apple' print(word.find(char)) |
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.
1 2 3 4 5 6 7 8 |
#Python code def check_char(word, char): if char in word: return True, word.count(char), word.find(char) else: return False, 0, -1 print(check_char('apple', 'a')) |
The complete code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Using the 'in' keyword char = 'a' word = 'apple' print(char in word) # Using the count() method char = 'a' word = 'apple' print(word.count(char)) # Using the find() method char = 'a' word = 'apple' print(word.find(char)) # Combining methods def check_char(word, char): if char in word: return True, word.count(char), word.find(char) else: return False, 0, -1 print(check_char('apple', 'a')) |
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!