Check a string for a specific character in Python
This post will discuss how to check a string for a specific character in Python.
1. Using in operator
The Pythonic, fast way to check for the specific character in a string uses the in operator. It returns True if the character is found in the string and False otherwise.
|
1 2 3 4 5 6 7 8 9 10 |
if __name__ == '__main__': s = "techiedelight.com" ch = '.' if ch in s: print("Character found") else: print("Character not found") |
The in operator implement the built-in function __contains__. It is not a good practice to call directly.
|
1 2 3 4 5 6 7 8 9 10 |
if __name__ == '__main__': s = "techiedelight.com" ch = '.' if s.__contains__(ch): print("Character found") else: print("Character not found") |
2. Using str.find() function
Another common approach to search for a character in the string is using the str.find() function. This returns the index of the first occurrence of the character in the string and -1 when the character is not found.
|
1 2 3 4 5 6 7 8 9 10 |
if __name__ == '__main__': s = "techiedelight.com" ch = '.' if s.find(ch) != -1: print("Character found") else: print("Character not found") |
3. Using Regex
Another approach is to use the regex, as demonstrated below. Note that regular expressions are costly and should be avoided whenever possible.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import re if __name__ == '__main__': s = "techiedelight.com" pattern = re.compile(r'.') if pattern.findall(s): print("Character found") else: print("Character not found") |
That’s all about checking a string for a specific character 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 :)