How to Check If String Contains Substring in Python
To check if a string contains a substring in Python, you can use the in operator, the find() function, or the re module.
The following examples show how to check if a string contains a substring in Python.
Using in Operator
We can use the in operator to check if a string contains a substring.
Suppose we have the following string:
# Declare string
string = "Hello, world!"
substring = "world"
# Check if the substring exists in the string
if substring in string:
print("The substring exists in the string.")
else:
print("The substring does not exist in the string.")
Output: 👇️
The substring exists in the string.
In this example, we use the in operator to check if the substring “world” exists in the string string.
Using find() Function
We can use the find() function to check if a string contains a substring.
Suppose we have the following string:
# Declare string
string = "Hello, world!"
substring = "world"
# Check if the substring exists in the string
if string.find(substring) != -1:
print("The substring exists in the string.")
else:
print("The substring does not exist in the string.")
Output: 👇️
The substring exists in the string.
In this example, we use the find() function to check if the substring “world” exists in the string string. If the substring is found, the function returns its starting index; otherwise, it returns -1.
Using re Module
We can use the re module to check if a string contains a substring.
Suppose we have the following string:
import re
# Declare string
string = "Hello, world!"
substring = "world"
# Check if the substring exists in the string
if re.search(r'world', string):
print("The substring exists in the string.")
else:
print("The substring does not exist in the string.")
Output: 👇️
The substring exists in the string.
In this example, we use the re.search() function from the re module to check if the substring “world” exists in the string string.
Conclusion
We can use the in operator, the find() function, and the re module to check if a string contains a substring in Python.