In Python programming, there are times when you need to check if a specific symbol or character is present in a string. This check can be performed in multiple ways. In this tutorial, “How to Check If a String Contains a Symbol in Python”, we will explore two common methods: the in keyword and find() function.
Method 1: Using the “in” keyword
The ‘in’ keyword in Python is often used to check if an item is present in a list or other iterable. However, it can also be used to check if a string contains a certain symbol or substring. Here’s how to use it:
1 2 |
text = 'Hello, World!' print(',' in text) |
True
In this example, we are checking whether the string ‘Hello, World!’ contains the symbol ‘,’. The ‘in’ keyword checks all elements of the string and returns True if at least one instance of the symbol is found. Otherwise, it returns False.
Method 2: Using the “find()” Function
The find() function in Python is a built-in method of the string type that returns the index of a substring within the string if found. If the substring is not found, it returns -1. Here’s how to use it:
1 2 |
text = 'Hello, World!' print(text.find(',')) |
In the example above, the find function will return the index of the symbol ‘,’ if it exists in the string ‘Hello, World!’. If the symbol isn’t found, the function will return -1.
5
From the output, we see that in the first method using ‘in’, the symbol ‘,’ was found and hence it returned True. In the second method using ‘find()’, it returned the index of the symbol ‘,’ which was 5.
Checking a Series of Symbols
You can also check for multiple symbols at once using either of these methods. For instance:
1 2 3 4 5 |
text = 'Hello, World!' symbols = ['!', ',', '.'] for symbol in symbols: print(symbol, ':', symbol in text) |
This code will check if each symbol in the list ‘symbols’ is found in the string ‘text’. It will print out each symbol along with the result of the check.
! : True , : True . : False
Complete Code
1 2 3 4 5 6 7 8 9 10 11 |
# Check with 'in' text = 'Hello, World!' print(',' in text) # Check with 'find()' print(text.find(',')) # Check series of symbols symbols = ['!', ',', '.'] for symbol in symbols: print(symbol, ':', symbol in text) |
Conclusion
It’s quite simple to check if a string contains a symbol in Python using either the ‘in’ keyword or the ‘find()’ function. While the ‘find()’ function provides additional information such as the index, the ‘in’ keyword is more straightforward and ideal for simple checks.
Keep practicing and experimenting with these methods to become more comfortable with string manipulation tasks in Python. Happy coding!