Check whether a Python string contains a substring

Use in for substring checks, find or index for positions, and casefold for caseless matching. Avoid confusing a zero position with a failed search.

Best practices
Python programming and application logging

Use needle in text to check whether one string contains another. It returns a Boolean and matches the literal substring, including punctuation and spaces.

text = "hello world"
print("world" in text)   # True
print("python" in text)  # False

Get a position or count

print(text.find("world"))   # 6
print(text.find("Python"))  # -1
print(text.index("world"))  # 6
print(text.count("o"))      # 2

index() raises ValueError when there is no match; find() returns -1. Do not use if text.find(needle): as a membership check: a match at position zero is false in a Boolean context, while -1 is true. count() counts non-overlapping occurrences.

Ignore case

Normalize both operands, not just the text:

log_line = "ERROR: connection closed"
needle = "error"
print(needle.casefold() in log_line.casefold())  # True

lower() is often sufficient for ASCII log labels. casefold() handles more Unicode caseless comparisons, although it does not perform Unicode normalization. Positions in transformed text need not correspond to positions in the original.

Match any of several substrings

log_line = "Request failed with an exception"
keywords = ["error", "fail", "exception"]
matched = any(word in log_line.casefold() for word in keywords)
print(matched)  # True

This detects substrings, so "fail" also matches "failed". For word boundaries or a pattern, use a regular expression, such as re.search(r"\berr\w*", text, re.IGNORECASE) after importing re.

FAQ

Does an empty substring match? Yes. "" in text is always true, including when text is empty. Reject an empty search term if that is not useful for your application.

Should I use a regex for speed? Use in for literal membership and regexes for pattern matching. For repeated searches across large datasets, measure a representative workload; a compiled regex is not automatically faster than literal search.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting