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 is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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