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():

# 6

# -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:

# 6

# ValueError: substring not found

FREE VS Code / PyCharm Extensions I Use

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

PySaaS: The Pure Python SaaS Starter Kit

馃殌 Build a software business faster with pure Python: Link*

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