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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap