Sub topic 2
Checking whether text contains a substring
This chapter assumes you know basic Python syntax, string literals and indexing, lists and tuples, and simple if statements and for loops. It covers the in operator, the simplest way to ask whether one string appears inside another.
The in and not in operators
A substring is a run of consecutive characters inside a larger string. The expression sub in text returns True if sub appears anywhere in text. Otherwise it returns False.
text = "Hello, World"
print("World" in text) # True
print("lo, W" in text) # True
print("xyz" in text) # False
print("xyz" not in text) # Truenot in is the negated form. Write "xyz" not in text rather than not "xyz" in text. Both work, but the first reads as one idea.
The match is exact and case-sensitive. The check also does not care where the match sits, so it can be at the start, in the middle, or at the end.
text = "Hello, World"
print("world" in text) # False, because the case differs
print("H" in text) # True
print("d" in text) # TrueWhat counts as a match
Three details are easy to get wrong.
- The empty string is a substring of every string, so
"" in textis alwaysTrue. This matters when the search term comes from user input and may be blank. - Spaces and punctuation are ordinary characters.
"o W" in "Hello, World"isTrue, and"oW" in "Hello, World"isFalse. - The left side must be a string. Using another type raises
TypeError.
text = "Order 66"
print("" in text) # True
print("r 6" in text) # True
try:
print(66 in text)
except TypeError as error:
print("TypeError:", error)To search for a number, convert it first with str(66) in text.
Strings versus lists
The same operator behaves differently on a list. On a string, in looks for a substring. On a list, it looks for an element that equals the left side.
word = "ab"
print(word in "abc") # True, because "ab" is inside "abc"
print(word in ["abc", "x"]) # False, because no element equals "ab"
print(word in ["ab", "x"]) # TrueThis difference causes bugs when a variable that you expected to be a list is actually a single string. A check such as "admin" in roles can pass for roles = "administrator" even though no role is named admin.
Using in to filter text
Because in returns a Boolean, it fits naturally into if statements and list comprehensions.
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']
for line in lines:
if "retry" in line:
print("retry found:", line)Choosing between in and other methods
in answers only a yes/no question. If you need a position, a count, or a check limited to the start or end of the string, later chapters cover better tools.
| Question | Tool |
|---|---|
| Does the text appear anywhere? | `in` |
| Where does it appear? | `find`, `index` |
| How many times does it appear? | `count` |
| Does the string start or end with it? | `startswith`, `endswith` |
Common errors
- Expecting a case-insensitive match.
"error" in "ERROR"isFalse. Normalizing case is covered in a later chapter. - Passing a non-string on the left side, which raises
TypeError. - Forgetting that an empty search term always matches.
- Confusing substring checks with list element checks.
Exercise
What do these three expressions print, and why? print("" in "abc"), print("ab" in ["abc"]), print("ab" in "abc")
Show answer
They print True, False, True. The empty string is a substring of every string. On a list, in compares whole elements, and "ab" does not equal "abc". On a string, in looks for a substring, and "ab" appears at the start of "abc".
Exercise
Write a list comprehension that keeps the names from names = ["report.csv", "notes.txt", "data.csv"] that contain the text "csv".
Show answer
[n for n in names if "csv" in n] returns ['report.csv', 'data.csv'].