How to check if a string contains a substring in Python
Use the `in` operator: "sub" in my_string returns True if the substring is present.
text = "The quick brown fox"
if "brown" in text:
print("found")
else:
print("not found")The snippet assigns a sample string to `text` and uses the membership test operator `in` to check whether the literal "brown" appears anywhere inside it. If the test is true the code prints "found", otherwise it prints "not found". The `in` operator is O(n) in the length of the string, runs in C, and works for Unicode without extra work, making it the idiomatic and fastest way in pure Python. A common gotcha is that `in` checks for a substring, not a whole word; use word boundaries or split if you need exact word matches.
Variations
Using str.find()
text = "abc"
idx = text.find("b")
if idx != -1:
print("found")find() returns the index or -1; slower than `in` and less readable.
Case-insensitive check
text = "Hello World"
sub = "hello"
if sub.lower() in text.lower():
print("found")Convert both strings to the same case; beware of locale-specific case folding.
Testing multiple substrings
text = "hello world"
needles = ["hi", "world"]
if any(n in text for n in needles):
print("match")any() short-circuits on the first match, useful for whitelist checks.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.