Automate everyday tasks with Python · Lesson 9 of 14

Clean up messy text

Tidy text that people typed or programs exported: strip spaces, fix case, replace characters, compare names safely and remove accents.

About 14 minutes · code runs in your browser, nothing to install

Data typed by people is messy: extra spaces, random capitals, different spellings of the same thing. Before a script can count, compare or sort text, it has to clean it. Python's string methods do most of the work, and they never change the original string: each one returns a new, cleaned copy.

Spaces

str.strip() removes spaces, tabs and new lines at both ends. Spaces in the middle need a different trick: str.split() with no argument splits on any run of spaces, and str.join() glues the pieces back with exactly one space.

Pythoneditable
raw = "   Anna    Maria\t Rossi  \n"

print(repr(raw.strip()))
print(repr(" ".join(raw.split())))
Output
'Anna    Maria\t Rossi'
'Anna Maria Rossi'

Upper and lower case

str.title() capitalises the first letter of every word, str.lower() and str.upper() change everything. To compare text without caring about case, use str.casefold(), which also handles letters like the German ß.

Pythoneditable
names = ["aNNA-lena o'brien", "JOSÉ GARCÍA", "li wei"]
for name in names:
    print(name.title())

print("Straße".lower() == "STRASSE".lower())
print("Straße".casefold() == "STRASSE".casefold())
Output
Anna-Lena O'Brien
José García
Li Wei
False
True

Replacing characters

str.replace() swaps every copy of one piece of text for another. Chained calls fix several problems in a row. To build a safe file name, turn everything that is not a letter or digit into a space, then join the words with underscores.

Pythoneditable
phone = "(030) 555-12 34"
digits = phone.replace("(", "").replace(")", "").replace("-", "").replace(" ", "")
print(digits)

title = "Q1 report: sales/costs (final)?"
words = "".join(ch if ch.isalnum() else " " for ch in title).split()
print("_".join(words) + ".txt")
Output
0305551234
Q1_report_sales_costs_final.txt

Accents and invisible differences

The letter é can be stored in two ways: as one character, or as e followed by a separate accent mark. Both look identical on screen but are not equal in Python. unicodedata.normalize("NFC", text) turns every text into the one-character form, so comparisons work. The NFKD form splits letters from their accents, which lets you remove accents completely, for example to build web addresses or file names.

Pythoneditable
import unicodedata

a = "Café"
b = "Cafe\u0301"          # e + combining accent
print(a, b, a == b, len(a), len(b))
print(unicodedata.normalize("NFC", a) == unicodedata.normalize("NFC", b))

def remove_accents(text):
    parts = unicodedata.normalize("NFKD", text)
    return "".join(ch for ch in parts if not unicodedata.combining(ch))

print(remove_accents("Crème brûlée in Zürich, São Paulo"))
Output
Café Café False 4 5
True
Creme brulee in Zurich, Sao Paulo

Putting it together

A cleaning function applies all the steps in a fixed order. Using it on a list of city names typed by different people turns seven spellings into four names. Sao Paulo without the accent still counts separately: for display keep accents, for matching you might compare remove_accents(name).casefold() instead.

Pythoneditable
import unicodedata

def clean(text):
    text = unicodedata.normalize("NFC", text)
    text = " ".join(text.split())
    return text.title()

typed = ["  são paulo", "SÃO PAULO ", "Sao Paulo", "new  york", "New York", "lima", " LIMA"]
counts = {}
for city in typed:
    c = clean(city)
    counts[c] = counts.get(c, 0) + 1

for city in sorted(counts):
    print(city, counts[city])
Output
Lima 2
New York 2
Sao Paulo 1
São Paulo 2

✎ Exercise

Clean the list emails: remove spaces at both ends, make everything lower case, and drop duplicates while keeping the first-seen order. Print the clean list, then how many were removed as <n> duplicates removed.

Hint: strip() and lower() each address, then append it only if it is not already in the new list.

Your codewrite your answer, then Run
emails = [" [email protected]", "[email protected] ", "[email protected]", "[email protected]", "[email protected]"]
# your code here

Expected output:

['[email protected]', '[email protected]', '[email protected]']
2 duplicates removed
Show a solution
Solutioneditable
emails = [" [email protected]", "[email protected] ", "[email protected]", "[email protected]", "[email protected]"]
clean = []
for e in emails:
    e = e.strip().lower()
    if e not in clean:
        clean.append(e)
print(clean)
print(len(emails) - len(clean), "duplicates removed")
Output
['[email protected]', '[email protected]', '[email protected]']
2 duplicates removed

Check yourself

1. What does " ".join("a b c".split()) give?

2. Which method is best for comparing text without caring about case?

3. Why can two strings that look identical be unequal?

Spotted a mistake on this page? Tell us