Checking if a string contains a substring in Python is a common task and can be accomplished in several ways. Here are a few examples:
- Using the
in
keyword: This is the most basic and easiest way to check if a string contains a substring. Thein
keyword returns a Boolean value ofTrue
if the substring is found in the string, andFalse
otherwise.
string = "Hello World"
substring = "World"
result = substring in string
print(result) # Output: True
- Using the
find()
method: Thefind()
method returns the index of the first occurrence of the substring in the string. If the substring is not found, it returns -1.
string = "Hello World"
substring = "World"
result = string.find(substring)
if result != -1:
print(f"{substring} found in {string} at index {result}")
else:
print(f"{substring} not found in {string}")
- Using the
index()
method: Theindex()
method returns the index of the first occurrence of the substring in the string. If the substring is not found, it raises aValueError
string = "Hello World"
substring = "World"
try:
result = string.index(substring)
print(f"{substring} found in {string} at index {result}")
except ValueError:
print(f"{substring} not found in {string}")
- Using Regular Expressions: You can use the
re
module to check if a string contains a substring using regular expressions. Thesearch()
method returns a match object if the substring is found in the string, andNone
otherwise.
import re
string = "Hello World"
substring = "World"
result = re.search(substring, string)
if result:
print(f"{substring} found in {string}")
else:
print(f"{substring} not found in {string}")
It’s important to note that all of these methods are case-sensitive, which means they will not find the substring if the case is different. If you want to check if a string contains a substring regardless of case, you can convert the string and the substring to lowercase using the lower()
method before checking for the presence of the substring.