Skip to content

Simplify substring search

Description:

Simplify finding if substrings are present in strings by using in

Before:

my_str = "Hello world"
if my_str.find("ello") == -1:
    print("Not Found!")

After:

my_str = "Hello world"
if "ello" not in my_str:
    print("Not Found!")

Before:

my_str = "Hello world"
if my_str.count("ello") > 0:
    print("Found!")

After:

my_str = "Hello world"
if "ello" in my_str:
    print("Found!")

Explanation:

Making use of Python's in operator for detecting if a substring is present in a string is more readable than using the find or count methods, and is also suggested in the documentation. These methods are more suitable for cases where you need more information about the substring's location or the number of times it appears.