w3resource

Checking substrings in Python: Methods and examples

What is the best way to check whether a string contains a specific substring in Python?

Python has several ways to check whether a string contains a specific substring. Each approach has its advantages and is suitable for different applications. Here are some common methods to check for substrings in a string:

Using the in keyword:

The in keyword can be used to check if a substring is present in a string. It returns a Boolean value (True or False) indicating whether the substring exists.

Code:

str1 = "Good, Morning!"
# Check if the substring exists
if "Morning" in str1:
    print("Substring found.")
else:
    print("Substring not found.")

Output:

Substring found.

Using the str.find() method:

The str.find() method is used to get the index of the first occurrence of the substring in the string. If the substring is not found, it returns -1.

Code:

my_string = "Good Morning!"
# Check if the substring exists and get its index
index = my_string.find("Morning")
if index != -1:
    print(f"Substring found at index {index}.")
else:
    print("Substring not found.")

Output:

Substring found at index 5.

Using the str.index() method:

The str.index() method is similar to str.find(), but if the substring is not found, it raises a ValueError. When using this method, it is essential to handle exceptions.

Code:

str1 = "Good, Morning!"

try:
    index = str1.index("Morning")
    print(f"Substring found at index {index}.")
except ValueError:
    print("Substring not found.")
Output:
Substring found at index 6.

Code:

str1 = "Good, Morning!"

try:
    index = str1.index("Morningg")
    print(f"Substring found at index {index}.")
except ValueError:
    print("Substring not found.")

Output:

Substring not found.

Using Regular Expressions (re module):

Using regular expressions from the re module, we can check for substrings in more complex patterns.

Code:

import re
str1 = "Good, Morning!"
# Use a regular expression to check for the substring
if re.search(r"Morning", str1):
    print("Substring found.")
else:
    print("Substring not found.")

Output:

Substring found.

Using String Slicing:

You can use string slicing to check if a substring exists by extracting a part of the string.

Code:

str1 = "Good, Morning!"

# Check if the substring exists using string slicing
sub_string = "Morning"
if sub_string in str1[:len(str1)]:
    print("Substring found.")
else:
    print("Substring not found.")


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-interview/what-is-the-best-way-to-check-whether-a-string-contains-a-specific-substring-in-python.php