Skip to main content

How to check if a string contains a specific substring in Python

How to check if a string contains a specific substring in Python.

Here's a step-by-step tutorial on how to check if a string contains a specific substring in Python:

Step 1: Start by defining the string you want to search in. Let's call it main_string.

Step 2: Define the substring you want to check for. Let's call it sub_string.

Step 3: Use the in operator to check if the sub_string is present in the main_string. The in operator returns True if the substring is found and False otherwise.

main_string = "Hello, World!"
sub_string = "Hello"

if sub_string in main_string:
print("Substring found!")
else:
print("Substring not found.")

Output:

Substring found!

Step 4: If you want to perform a case-insensitive search, use the lower() method to convert both the main_string and sub_string to lowercase before checking for the substring.

main_string = "Hello, World!"
sub_string = "hello"

if sub_string.lower() in main_string.lower():
print("Substring found!")
else:
print("Substring not found.")

Output:

Substring found!

Step 5: To find the position/index of the substring within the main string, you can use the find() method. It returns the index of the first occurrence of the substring, or -1 if the substring is not found.

main_string = "Hello, World!"
sub_string = "World"

index = main_string.find(sub_string)

if index != -1:
print(f"Substring found at index {index}")
else:
print("Substring not found.")

Output:

Substring found at index 7

Step 6: If you want to check for multiple occurrences of the substring, you can use a loop to iterate over the string and check for each occurrence.

main_string = "Hello, Hello, Hello!"
sub_string = "Hello"

occurrences = []

start = 0
while True:
index = main_string.find(sub_string, start)
if index == -1:
break
occurrences.append(index)
start = index + 1

if occurrences:
print(f"Substring found at indices: {occurrences}")
else:
print("Substring not found.")

Output:

Substring found at indices: [0, 7, 14]

That's it! You now know how to check if a string contains a specific substring in Python.