How can I check if a string contains a substring in Python?

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:

  1. Using the in keyword: This is the most basic and easiest way to check if a string contains a substring. The in keyword returns a Boolean value of True if the substring is found in the string, and False otherwise.
string = "Hello World"
substring = "World"
result = substring in string
print(result)  # Output: True
  1. Using the find() method: The find() 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}")
  1. Using the index() method: The index() method returns the index of the first occurrence of the substring in the string. If the substring is not found, it raises a ValueError
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}")
  1. Using Regular Expressions: You can use the re module to check if a string contains a substring using regular expressions. The search() method returns a match object if the substring is found in the string, and None 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.

Leave a Reply