How to check if a String contains a Substring in Python

Learn how to check if a String contains a Substring in Python and how to get the position.


Learn how to check if a string contains a substring in Python and how to get the position of the substring.

Python does not have a string.contains() method. However, to check if a string contains a substring, you can simply use the if x in my_string syntax:

my_string = "Hello World"
if "World" in my_string:
    print("has substring")

This check is case sensitive!

If you also need to know the position of the substring, you can use string.find():

my_string.find("World")
# 6

my_string.find("Earth")
# -1
From the official Python docs:

str.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

So be aware that if the string contains multiple substrings, str.find() still only returns the index of the first found index.

str.index(x[, start[, end]]) can also be used and works the same way as str.find() except that it raises a ValueError if the substring is not found, instead of returning -1:

my_string.index("World")
# 6

my_string.index("Earth")
# ValueError: substring not found

FREE VS Code / PyCharm Extensions I Use

鉁 Write cleaner code with Sourcery, instant refactoring suggestions: Link*

* This is an affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 馃檹