Skip to main content

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

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

Here is a step-by-step tutorial on how to check if a string contains a certain substring in Python:

Step 1: Start by defining the main string and the substring you want to check for. For example, let's say our main string is "Hello, World!" and the substring is "Hello".

Step 2: Use the in operator to check if the substring exists within the main string. The in operator returns a Boolean value (True or False) indicating whether the substring is present or not. Here's an example code snippet:

main_string = "Hello, World!"
substring = "Hello"

if substring in main_string:
print("Substring exists in the main string")
else:
print("Substring does not exist in the main string")

Output:

Substring exists in the main string

Step 3: If you want to perform a case-insensitive check, you can convert both the main string and the substring to lowercase using the lower() method before performing the check. This ensures that the check is not affected by the case of the characters. Here's an example:

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

if substring.lower() in main_string.lower():
print("Substring exists in the main string (case-insensitive)")
else:
print("Substring does not exist in the main string (case-insensitive)")

Output:

Substring exists in the main string (case-insensitive)

Step 4: If you want to find the position/index of the substring within the main string, you can use the find() method. The find() method returns the index of the first occurrence of the substring, or -1 if the substring is not found. Here's an example:

main_string = "Hello, World!"
substring = "World"

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

Output:

Substring found at index 7

Step 5: If you want to count the number of occurrences of a substring within the main string, you can use the count() method. The count() method returns the number of non-overlapping occurrences of the substring. Here's an example:

main_string = "Hello, Hello, Hello!"
substring = "Hello"

count = main_string.count(substring)
print(f"Number of occurrences: {count}")

Output:

Number of occurrences: 3

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