Almost every text problem is solved by combining a few patterns. Recognizing them saves you a lot of time.
Pattern: counting
text = "mississippi"
print(text.count("s")) # 4
print(text.count("ss")) # 2
vowels = 0
for c in text:
if c in "aeiou":
vowels += 1
print(vowels) # 4
The expression c in "aeiou" checks whether a character is a vowel without writing five comparisons.
Pattern: grouping consecutive equal characters
To compress text, such as aaabcc → a3b1c2, you remember the current character and how many times it has been repeated:
text = "aaabcc"
result = ""
current = text[0]
count = 1
for c in text[1:]:
if c == current:
count += 1
else:
result += current + str(count)
current = c
count = 1
result += current + str(count) # the last group!
print(result) # a3b1c2
Notice the final line: the last group is not written inside the loop, so it has to be added afterwards. Forgetting it is a very common mistake.
Pattern: validating with flags
To check several conditions on a text, you go through the characters once and store boolean flags:
password = "Abcdefg1"
has_upper = False
has_digit = False
for c in password:
if c.isupper():
has_upper = True
if c.isdigit():
has_digit = True
print(len(password) >= 8 and has_upper and has_digit) # True
Pattern: initials and first letters
sentence = "Portable Network Graphics"
initials = ""
for word in sentence.split():
initials += word[0].upper()
print(initials) # PNG
Pattern: a string as the key of a dictionary
sentence = "abracadabra"
frequency = {}
for c in sentence:
frequency[c] = frequency.get(c, 0) + 1
print(frequency) # {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
Common mistakes
Trying to modify a string. Strings are immutable:
word = "hello"
word[0] = "H"
# TypeError: 'str' object does not support item assignment
word = "H" + word[1:] # correct: create a new string
Forgetting to assign the result. The methods return the new string, they do not change the original:
text = " hello "
text.strip() # does nothing visible: the result is discarded
text = text.strip() # correct
Going out of range. With an empty text, text[0] raises IndexError. Check first that it is not empty:
text = ""
if text:
print(text[0])
print(text[:1]) # a slice never fails: it gives an empty string
Mixing text and numbers. "age: " + 30 gives TypeError. Use an f-string or str():
age = 30
print(f"age: {age}") # age: 30
print("age: " + str(age)) # age: 30
Comparing texts with numbers. "10" < "9" is True, because they are compared character by character. Convert with int() before comparing numeric values.
Accented letters. Some operations, such as ord(c) - ord("a"), only work with the letters of the English alphabet. With ñ or é they will give unexpected results: keep it in mind when designing the program.
Review what you learned with Text compression and Validate password.