0
0
PythonHow-ToBeginner · 3 min read

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: Returns True if substring exists, else False.
  • string.find(substring): Returns the lowest index of substring or -1 if not found.
  • string.index(substring): Returns the lowest index of substring or raises ValueError if 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 handling ValueError if substring is missing.
  • Confusing find() returning -1 with a valid index.
  • Assuming in returns 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

MethodDescriptionReturn Value if FoundReturn Value if Not Found
inCheck if substring existsTrueFalse
str.find()Find lowest index of substringIndex (int)-1
str.index()Find lowest index of substringIndex (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.