Python string does not have a built-in .contains() method like some other languages (e.g., Java), but you can easily check if a substring exists using below methods.
Method 1: Use the in Keyword (Recommended)
This is the most Pythonic way to check if a substring exists in a string.
python
text = “hello world”if “world” in text:
print(“Yes, found!”)
Best for clean, readable code in most use cases.
Method 2: Use .find() Method
Returns the starting index of the substring if found, or -1 if not found.
python
text = “hello world”if text.find(“world”) != -1:
print(“Found using .find()”)
Useful when you need the position of the substring.
Method 3: Use .index() Method
Similar to .find(), but raises a ValueError if the substring is not found.
python
text = “hello world”try:
index = text.index(“world”)
print(“Found at index:”, index)
except ValueError:
print(“Substring not found”)
Use this if you’re okay handling exceptions.
Also Read:
Tip
Always prefer the in keyword for simplicity. Use .find() or .index() only when you need the index position or want to handle absence explicitly.