Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check if a substring is contained in another string in Python?
In Python, you can check whether a substring exists within another string using the in operator, or string methods like find(), index(), and __contains__().
A string in Python is a sequence of characters enclosed in quotes. You can use either single quotes '...' or double quotes "..." ?
text1 = "Hello" # double quotes text2 = 'Python' # single quotes print(text1) print(text2)
Hello Python
A substring is simply a part of a string. For example ?
text = "Python"
substring = "tho"
print(f"'{substring}' is a substring of '{text}'")
'tho' is a substring of 'Python'
Using the in Operator
The in operator is the most common and readable way to check if a substring exists. It returns True if found, False otherwise ?
text = "Python is fun" result = "Python" in text print(result) # Check for non-existing substring result2 = "Java" in text print(result2)
True False
Using the find() Method
The find() method returns the starting index of the first occurrence of the substring. If not found, it returns -1 ?
text = "Python is fun"
index = text.find("fun")
print(f"'fun' found at index: {index}")
# Check for non-existing substring
index2 = text.find("Java")
print(f"'Java' found at index: {index2}")
'fun' found at index: 10 'Java' found at index: -1
Using the index() Method
The index() method works like find() but raises a ValueError if the substring is not found ?
text = "Python is fun"
position = text.index("is")
print(f"'is' found at position: {position}")
'is' found at position: 7
Handling ValueError with index()
Use try-except to handle the exception when substring is not found ?
text = "Python is fun"
try:
position = text.index("Java")
print(f"Found at position: {position}")
except ValueError:
print("Substring not found.")
Substring not found.
Using __contains__() Method
The __contains__() method is what Python calls internally when you use the in operator ?
text = "Python is fun"
result = text.__contains__("fun")
print(result)
True
Using Regular Expressions
For pattern matching and complex searches, use the re module ?
import re
text = "Python is fun"
if re.search("fun", text):
print("Found")
else:
print("Not found")
# Pattern matching example
if re.search(r"\bfun\b", text): # Word boundary
print("'fun' found as complete word")
Found 'fun' found as complete word
Comparison
| Method | Returns | Error Handling | Best For |
|---|---|---|---|
in |
Boolean | No exceptions | Simple existence check |
find() |
Index or -1 | Returns -1 | When you need position |
index() |
Index | Raises ValueError | When substring must exist |
re.search() |
Match object | Returns None | Pattern matching |
Conclusion
Use the in operator for simple substring checks. Use find() when you need the position and want to avoid exceptions. Use re.search() for pattern-based searches.
