About this question
Python doesn't have a dedicated contains() method for strings, but you can easily check substrings using alternatives like the in operator or the find() method. Learn how to perform substring checks effectively in Python!
Python doesn't have a dedicated contains() method for strings, but you can easily check substrings using alternatives like the in operator or the find() method. Learn how to perform substring checks effectively in Python!
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask Python Expert
Answered on Mar 27, 2025
No, Python doesn’t have a built-in contains() method for strings, which can surprise those coming from other programming languages. However, Python provides several simple and effective ways to check if a string contains a substring.
Here are some alternatives you can use:
Using the in operator (most common and readable)
This is the Pythonic way to check for substrings. It’s straightforward and easy to understand.
text = "Hello, world!"
if "world" in text:
print("Substring found!")Using the find() method
The find() method returns the index of the substring if found, or -1 if it’s not present.
text = "Python is fun"
if text.find("fun") != -1:
print("Substring found!")Using the index() method
Similar to find(), but it raises a ValueError if the substring is not found.
try:
position = text.index("Python")
print("Substring found at index:", position)
except ValueError:
print("Substring not found.")Using Regular Expressions (for advanced searches)
Regular expressions allow more complex substring matching.
import re
if re.search("Python", text):
print("Substring found!")Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Most-read guides across JanBask
Common Python interview questions, answered
Guides, tips and career advice on Python from JanBask experts.
Python How to Become a Python Developer: A Step-by-Step Guide for Beginners
Discover how to become a Python Developer via a practical 7-step guide build projects, maintain clean code, practice daily, and…
Python PCEP Certification Guide: Entry-Level Python Programmer Certification
Explore this PCEP certification guide for insights on cost, exam format, passing score, application, training, and study tips.…
Python Top 50+ Python Projects ideas for Beginners to Advanced
Discover innovative Python project ideas, explore advanced Python projects, and find good Python projects for beginners and…
Python How To Comment Out Multiple Lines In Python Like A Pro
Commenting out code is a common practice among programmers. It allows you to temporarily disable parts of your code without…