How to Find Substring in String in Python: Simple Guide
In Python, you can find a substring in a string using the
in keyword to check if it exists, or use str.find() and str.index() methods to get the position of the substring. find() returns -1 if not found, while index() raises an error.Syntax
Here are the common ways to find a substring in a string:
substring in string: ReturnsTrueif substring exists, elseFalse.string.find(substring): Returns the lowest index of substring or-1if not found.string.index(substring): Returns the lowest index of substring or raisesValueErrorif not found.
python
text = "hello world" # Check if substring exists exists = "world" in text # Find position of substring pos_find = text.find("world") pos_index = text.index("world")
Example
This example shows how to check if a substring exists and find its position using in, find(), and index().
python
text = "hello world" substring = "world" # Check existence if substring in text: print(f"'{substring}' found in text") else: print(f"'{substring}' not found in text") # Find position with find() pos = text.find(substring) print(f"Position using find(): {pos}") # Find position with index() pos2 = text.index(substring) print(f"Position using index(): {pos2}")
Output
'world' found in text
Position using find(): 6
Position using index(): 6
Common Pitfalls
Common mistakes include:
- Using
index()without handlingValueErrorif substring is missing. - Confusing
find()returning-1with a valid index. - Assuming
inreturns the position instead of a boolean.
python
text = "hello world" substring = "python" # Wrong: Using index() without try-except try: pos = text.index(substring) except ValueError: pos = -1 print(f"Position with index(): {pos}") # Correct: Using find() which returns -1 if not found pos_find = text.find(substring) print(f"Position with find(): {pos_find}")
Output
Position with index(): -1
Position with find(): -1
Quick Reference
| Method | Description | Return Value if Found | Return Value if Not Found |
|---|---|---|---|
| in | Check if substring exists | True | False |
| str.find() | Find lowest index of substring | Index (int) | -1 |
| str.index() | Find lowest index of substring | Index (int) | Raises ValueError |
Key Takeaways
Use
in to quickly check if a substring exists in a string.Use
str.find() to get the position or -1 if substring is missing.Use
str.index() when you want an error if substring is not found.Always handle
ValueError when using index() to avoid crashes.Remember
in returns a boolean, not the position.