Python String contains substring equivalent example

If you come from a Java programming background and wondering what is the alternative of String contains() or subString() methods in Python, well you can make use of the in operator.

Let's take a look at a few code examples.


Example 1:
string = "Cats rule the world!"
substring = "Cats"
if substring in string:
    print(f"Substring '{substring}' found")
else:
    print(f"Substring '{substring}' not found")

Example 2:
string = "I love dogs!"
substring = "dog"
if substring in string:
    print(f"Substring '{substring}' found")
else:
    print(f"Substring '{substring}' not found")

Example 3:
string = "I love dogs!"
substring = "Dog"
if string.find(substring) != -1:
    print(f"Substring '{substring}' found in string '{string}'")
else:
    print(f"Substring '{substring}' not found in string '{string}'")
Python Substring Example using find method

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!