To check if a string contains another string in Python, use the in operator.
if "word" in somestring: # do something
To also find the index at which the substring occurs, use the find() method of a string.
This returns the first index at which the substring “word” occurs. If no string is found, it returns -1.
Let’s see some examples.
Examples of Checking If a String Is a Substring of Another String
Let’s figure out if the word “This” occurs in a string:
sentence = "This is just a sentence" if "This" in sentence: print("Found it!")
Let’s then figure out the index at which it occurs:
sentence = "This is just a sentence. This is another." idx = sentence.find("This") print("The word 'This' begins at:", idx)
The word 'This' begins at: 0
As you can see, the find() method only cares about the first occurrence of the word “This” in the sentence.
An Edge Case
If you are using the in operator, check that the main string is not None. If you do no do that, you get an error.
sentence = None if "This" in sentence: print("Found it!")
TypeError: argument of type 'NoneType' is not iterable
To avoid this error, make sure to check against None like this:
sentence = None if sentence is not None and "This" in sentence: print("Found it!")
Today you learned how to check if a string contains a substring in Python.
- Use the in statement to check if a string is a substring of another string.
- Use the string’s built-in find() method to figure out the index at which the string starts in another string.
Thanks for reading. I hope you enjoy it.
50 Python Interview Questions with Answers
50+ Buzzwords of Web Development
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
- Artificial Intelligence2023.05.16Humata AI Review (2023): Best PDF Analyzer (to Understand Files)
- Python2023.05.139 Tips to Use ChatGPT to Write Code (in 2023)
- Artificial Intelligence2023.04.1114 Best AI Website Builders of 2023 (Free & Paid Solutions)