How to Check if String Contains Substring in Python
In Python, you can check if a string contains a substring using the
in keyword, like substring in string. This expression returns True if the substring is found and False otherwise.Syntax
The basic syntax to check if a substring exists in a string is:
substring in string: ReturnsTrueifsubstringis found insidestring.substring not in string: ReturnsTrueifsubstringis NOT found insidestring.
python
substring in string substring not in string
Example
This example shows how to check if the word 'cat' is inside a sentence string.
python
sentence = "The cat is sleeping on the sofa." if "cat" in sentence: print("Found 'cat' in the sentence.") else: print("'cat' not found in the sentence.")
Output
Found 'cat' in the sentence.
Common Pitfalls
One common mistake is using the wrong method like string.contains(substring), which does not exist in Python. Another is confusing in with methods like find() or index() which behave differently.
Also, remember that the in check is case-sensitive, so 'Cat' is different from 'cat'.
python
text = "Hello World" # Wrong way (will cause error): # if text.contains("World"): # print("Found") # Right way: if "World" in text: print("Found") # Case sensitivity example: if "world" in text: print("Found lowercase world") else: print("Did not find lowercase world")
Output
Found
Did not find lowercase world
Quick Reference
Use this quick guide to remember how to check substring presence:
| Operation | Description | Example | Result |
|---|---|---|---|
| Check substring | Returns True if substring is in string | "cat" in "concatenate" | True |
| Check substring absence | Returns True if substring is NOT in string | "dog" not in "concatenate" | True |
| Case sensitive | Check is case sensitive | "Cat" in "cat" | False |
Key Takeaways
Use the
in keyword to check if a substring exists in a string.The
in check returns a boolean: True if found, False if not.Remember that substring checks are case-sensitive in Python.
Avoid using non-existent methods like
contains() in Python strings.Use
not in to check if a substring is absent.