Does Python have a string ‘contains’ substring method?

Yes, Python has a straightforward way to check if a string contains a substring. Here are the common methods to achieve this:

1. Using the in Keyword (Most Common)

The simplest and most Pythonic way to check for a substring:

main_string = "Hello, welcome to Python programming"
substring = "Python"

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

Output:
Substring found!

2. Using str.find() (Returns Index or -1)

Returns the index of the first occurrence of the substring or -1 if not found:

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

Output:
Found at index 18

3. Using str.index() (Like find() but Raises an Error)

Similar to find(), but raises a ValueError if the substring is missing:

try:
    index = main_string.index(substring)
    print(f"Found at index {index}")
except ValueError:
    print("Not found")

4. Using str.__contains__() (Behind-the-Scenes for in)

The in keyword internally calls this method. Rarely used directly:

if main_string.__contains__(substring):
    print("Found")

Key Differences

MethodReturnsError HandlingUse Case
inTrue/FalseNone (safe)Simple existence check
str.find()Index (or -1)None (safe)Need position of substring
str.index()IndexRaises ValueError if missingStrict checks (require substring)
__contains__True/FalseNone (safe)Rarely used directly

Additional Notes

Case-Insensitive Check

if substring.lower() in main_string.lower():
    print("Found (case-insensitive)")

Check for Multiple Substrings

substrings = ["Python", "Java", "C++"]
if any(sub in main_string for sub in substrings):
    print("At least one substring exists")

Empty Substring Behavior

An empty substring ("") always returns True:

print("" in "abc")  # Output: True

Summary

  • Use in for simple existence checks (most readable).
  • Use find() if you need the substring’s position.
  • Avoid index() unless you explicitly want an error for missing substrings.
  • Case-insensitive checks can be done by converting both strings to the same case (e.g., .lower()).

Leave a Reply

Your email address will not be published. Required fields are marked *