Skip to content

Simplify substring search

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Section titled “Sourcery refactoring id: simplify-substring-search”

Simplify finding if substrings are present in strings by using in

my_str = "Hello world"
if my_str.find("ello") == -1:
print("Not Found!")
my_str = "Hello world"
if "ello" not in my_str:
print("Not Found!")
my_str = "Hello world"
if my_str.count("ello") > 0:
print("Found!")
my_str = "Hello world"
if "ello" in my_str:
print("Found!")

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.