Python Cleaning Text Data
Cleaning text data means fixing messy strings before use. Messy strings carry extra spaces, mixed case, and stray marks.
Cut the edge spaces
strip() drops the spaces at both ends. The name inside stays the same.
name = " ada lovelace "
print(name.strip())
print(len(name.strip()))Even out the case
lower() turns mixed case into one case. Two spellings of one name then match.
name = "Ada LOVELACE"
print(name.lower())
print(name.lower() == "ada lovelace")Swap one mark for another
replace() swaps every comma for a space. The words then sit apart.
line = "ada,lovelace,1820"
print(line.replace(",", " "))Fix it all in one line
The methods run left to right. Each one hands a cleaner string to the next.
raw = " ADA,LOVELACE "
print(raw.strip().lower().replace(",", " "))Example
raw = [" Ada Lovelace ", "BOB HOOPER", " cy lee ", "DEE HOPPER"]
clean = []
for name in raw:
fixed = name.strip().title()
fixed = fixed.replace(" ", " ")
clean.append(fixed)
print(clean)
print("First:", clean[0])
print("Count:", len(clean))Key points
- Clean text: strings fixed up before a program uses them
- Use strip() to cut spaces from both ends of a string
- Use lower() to turn every letter into lower case
- Use upper() to turn every letter into upper case
- Use replace(old, new) to swap one piece of text for another
- Use title() to cap the first letter of each word
- Chain the methods in one line when several fixes apply at once
In this example, the list holds four messy names. The loop takes one name at a time. strip() cuts the edge spaces, and title() caps each word. replace() turns a double space into one space. The clean list holds four tidy names, and the count of 4 proves none were lost.
Note
strip() cuts spaces at the ends only, so spaces inside the string stay put.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does " Ada ".strip() give back?