in Python How to Search for a Substring in a String
Published on Aug. 22, 2023, 12:15 p.m.
find()
To search for a substring in a string in Python, you can use the in
operator or the find()
method. Here’s an example:
my_string = "Hello, World!"
# Using the 'in' operator
if "Hello" in my_string:
print("Substring found")
else:
print("Substring not found")
# Using the 'find' method
if my_string.find("World") != -1:
print("Substring found")
else:
print("Substring not found")
The in
operator will return a boolean value depending on whether the substring is found or not, while the find()
method will return the index of the first occurrence of the substring or -1 if it’s not found.
re
Sure! Apart from using the in
operator or the find()
method, you can also use regular expressions to search for substrings in a string in Python. The re
module provides various functions to work with regular expressions. Here’s an example:
import re
my_string = "Hello, World!"
# Using regular expressions
if re.search("Hello", my_string):
print("Substring found")
else:
print("Substring not found")
In this example, we use the re.search()
function to look for the substring “Hello” in the original string. The function returns a match object if the substring is found, or None
if it’s not found.
index()
To match a substring to a string using the index in Python, you can use the index()
method. Here’s an example:
my_string = "Hello, World!"
try:
index = my_string.index("Hello")
print("Substring found at index:", index)
except ValueError:
print("Substring not found")
In this example, we try to find the index of the substring “Hello” in the original string using the index()
method. If the substring is found, the method returns its index. If the substring is not found, a ValueError
is raised, which we catch and print a relevant message.