Sub topic 2
Checking whether text contains a substring
This chapter assumes you know basic Python syntax, how str literals and indexing work, what lists and tuples are, and how to read simple if statements and for loops. It covers the in and not in operators on strings. These are the simplest way to ask whether one piece of text appears inside another.
What the operator does
A substring is a run of consecutive characters inside a longer string. The in operator returns True if the left string appears anywhere inside the right string. Otherwise it returns False.
s = "Hello, World"
print("World" in s) # True
print("world" in s) # False
print("o, W" in s) # True
print("xyz" not in s) # Truenot in is the negation. x not in s means the same as not (x in s), and it reads more naturally in conditions.
The result is a bool, so you can use it directly in an if statement:
line = "ERROR: disk full"
if "ERROR" in line:
print("needs attention")The operator does not tell you where the match is or how many matches exist. It answers only yes or no. Later chapters cover find and count for those questions.
Rules to remember
Four properties cause most of the surprises.
- The match is case-sensitive.
"world"is not found in"Hello, World". - The match is literal. Characters such as
.,*, and?mean themselves. There are no wildcards. - Position does not matter. The substring can be at the start, in the middle, or at the end.
- The empty string is always found. Every string contains
"".
s = "Hello, World"
print("" in s) # True
print("" in "") # True
print("." in "a.b") # True, a literal dot
print("a*" in "aaa") # False, * is not a wildcardThe empty-string rule matters when the text to look for comes from user input or a config file. If a user leaves a search box blank, query in text is True for every document. Check for an empty query first if you do not want that.
def matches(query, text):
if not query:
return False
return query in text
print(matches("", "anything")) # False
print(matches("any", "anything")) # TrueBoth sides must be strings
The in operator on a string requires a string on the left. Anything else raises TypeError.
try:
print(1 in "123")
except TypeError:
print("TypeError: left operand must be a str")
print(str(1) in "123") # TrueThis catches people who read numeric data from a file and compare it as if it were text. Convert with str() first, or compare the values as numbers.
The right side also has to be something that supports in. If a variable is None, "abc" in value raises TypeError, because None is not iterable. A common guard is to substitute an empty string:
value = None
print("abc" in (value or "")) # FalseThe same operator means different things on different types
The word in behaves differently depending on what is on the right. This is the most common source of confusion for intermediate learners.
| Expression | Right side is | What `in` tests |
|---|---|---|
| `"app" in "apple pie"` | a string | whether `"app"` is a substring |
| `"app" in ["apple", "pie"]` | a list | whether `"app"` equals one element exactly |
| `"app" in ("apple", "pie")` | a tuple | whether `"app"` equals one element exactly |
| `"app" in {"apple", "pie"}` | a set | whether `"app"` equals one element exactly |
words = ["apple", "banana"]
print("app" in words) # False: no element equals "app"
print("apple" in words) # True
print("app" in "apple banana") # True: substring of the stringIf a list check returns False when you expected True, ask whether you wanted an exact match on an element or a substring match inside the text.
Whole words versus substrings
Substring membership does not respect word boundaries. "at" is found inside "cat", "sat", and "mat".
sentence = "The cat sat on the mat"
print("at" in sentence) # True
print("cat" in sentence) # True
print("at" in sentence.split()) # False
print("cat" in sentence.split()) # TrueSplitting the sentence into a list of words and testing membership in the list gives a whole-word test. This works only when words are separated cleanly. Punctuation sticks to words:
sentence = "I saw a cat."
print("cat" in sentence.split()) # False, the word is "cat."
print("cat" in sentence) # TrueFor simple cases you can strip punctuation first. For real word-boundary matching, the final chapter explains why the re module is the better tool.
Case-insensitive checks
Because in is case-sensitive, normalize both sides to the same case before testing.
s = "Hello, World"
query = "WORLD"
print(query.lower() in s.lower()) # TrueConvert both sides, not just one. Converting only the text leaves a query such as "WORLD" unmatched.
lower() is enough for plain English text. For text in other languages, casefold() is the safer choice. A later chapter in this tutorial explains why.
Testing several candidates
A tuple on the left side of in does not work as "any of these". ("a", "b") in "abc" raises a TypeError, because the left operand is a tuple and not a string. To test several substrings, combine in with any() or all():
text = "Error: disk full"
keywords = ("disk", "memory")
print(any(k in text for k in keywords)) # True: at least one found
print(all(k in text for k in keywords)) # False: "memory" is missingany() stops at the first match, so it does not scan the text for the remaining keywords once it finds one. Compare this with startswith and endswith, which accept a tuple directly. in has no such shortcut.
Filtering collections of strings
Membership tests fit naturally into list comprehensions and loops.
lines = [
"INFO start",
"ERROR disk full",
"INFO retry",
"ERROR timeout",
]
errors = [line for line in lines if "ERROR" in line]
print(errors) # ['ERROR disk full', 'ERROR timeout']
clean = [line for line in lines if "ERROR" not in line]
print(clean) # ['INFO start', 'INFO retry']This pattern is fine for log scanning, simple search boxes, and data cleaning.
How it works internally
x in s for a string calls the method s.__contains__(x). You rarely need to call it yourself, but it explains why a wrong type on the left raises an error. CPython searches the string with an optimized substring algorithm, so the test is fast in practice. Cost grows with the length of the text, and a miss has to scan the whole string. If you test thousands of queries against one very large text, think about whether an index or a different data structure suits the job better.
Strings are immutable, so a membership test never changes the text. It only reads it.
Choosing the right tool
Use the diagram to decide which operation fits your question.
Prefer in over find(...) != -1 when you only need a yes or no answer. It is shorter and states the intent directly. A common mistake is writing if s.find("x"):. find returns -1 when the text is missing, and -1 is truthy. The same call returns 0 when the text is at the start, and 0 is falsy. The condition is therefore wrong in both cases. if "x" in s: avoids the problem.
s = "xyz"
print(bool(s.find("x"))) # False, even though "x" is present
print(bool(s.find("q"))) # True, even though "q" is absent
print("x" in s) # TrueCommon errors
- Forgetting that matching is case-sensitive, so
"Error" in "ERROR"isFalse. - Testing a list when you meant to test a string, or the reverse.
- Passing an
intorNoneas the left or right operand. - Treating an empty query as "no match" when it actually matches everything.
- Expecting
into match whole words. It matches any substring. - Putting a tuple of candidates on the left of
in.
Exercise
Write a function has_any(text, words) that returns True if any string in words appears in text, ignoring case, and returns False when words is empty. What does has_any("Disk FULL", ["full", "memory"]) return, and why does has_any("abc", [""]) return True?
Show answer
def hasany(text, words): lowered = text.lower() return any(w.lower() in lowered for w in words) hasany("Disk FULL", ["full", "memory"]) returns True. Both sides are lowercased, so "full" is found in "disk full". When words is empty, any() of an empty sequence is False. has_any("abc", [""]) returns True because the empty string is a substring of every string, so "" in "abc" is True.