API Navigator Logo

Checking if a Python String Contains a Substring

Author: Newtum

This guide shows the most Pythonic way to check if a string contains another string (a substring) using the `in` operator.

Using the `in` Operator

The `in` operator provides a clean and readable way to test for membership. It returns `True` if the substring is found within the string, and `False` otherwise.

main_string = "Hello, world! This is a test."
substring1 = "world"
substring2 = "python"

if substring1 in main_string:
    print(f"'{substring1}' is in the main string.")
else:
    print(f"'{substring1}' is NOT in the main string.")

if substring2 in main_string:
    print(f"'{substring2}' is in the main string.")
else:
    print(f"'{substring2}' is NOT in the main string.")

Case-Sensitive Checking

The `in` operator is case-sensitive. To perform a case-insensitive check, you can convert both strings to the same case (e.g., lowercase) before the comparison.

main_string = "Hello World"
substring = "hello"

# Case-sensitive check (False)
print(f"'hello' in 'Hello World'? {substring in main_string}")

# Case-insensitive check (True)
print(f"Case-insensitive check: {substring.lower() in main_string.lower()}")