Table of Contents
Python has plenty of built-in methods that make it easy to work with strings.
One of the most common tasks is to check if a string contains a substring, for example, if a string contains a specific word.
In this post, we'll learn how we can check if a string contains a substring in Python.
How to check if a string contains a substring in Python
To check if a string contains a substring in Python, we can use the in
operator.
The in
operator returns True
if the substring is found in the string, and False
if it's not.
First let's define example strings and substrings:
PYTHONstring = "Python is awesome"
substring = "awesome"
Now let's check if this substring is in the string:
PYTHONstring = "Python is awesome"
substring = "awesome"
if substring in string:
print("Substring found in string")
else:
print("Substring not found in string")
The output of the above code is:
BASHSubstring found in string
As expected, because the substring is in the string, the in
operator returned True
, and the if
statement was executed.
How to get the index of a substring in a string
If you want to get the index of the substring in the string, you can use the find()
method.
This method is called on the string and takes the substring as an argument.
The find()
method returns the index of the substring in the string if it's found, and -1
if it's not.
Let's see it in action:
PYTHONstring = "Python is awesome"
substring = "awesome"
index = string.find(substring)
if index != -1:
print(f"Substring found in string at index {index}")
else:
print("Substring not found in string")
BASHSubstring found in string at index 10
Conclusion
In this post, we learned how to check if a string contains a substring in Python.
Simply use the in
operator in between the string and the substring to get a boolean value.
Thanks for reading!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API