MyMisPal
← Python lessons
Lesson 10 of 13

Strings and data cleaning

Most real data is messy: extra spaces, mixed letter case and comma-separated values. String methods are your cleaning tools.

PYTHON
raw = "  sara AL-qahtani  "
clean = raw.strip().title()
print(clean)
print(clean.upper(), clean.lower())
print(len(raw), len(clean))
PYTHON
email = "Lina.Mansour@Company.com"
user, domain = email.lower().split("@")
print(user, domain)
print(email.endswith(".com"), "@" in email)
print(email.replace("Company", "mymispal"))

And here is a line from a CSV file being parsed:

PYTHON
line = "1001,Laptop,4800,3"
parts = line.split(",")
print(parts)
print(int(parts[2]) * int(parts[3]))
Watch outStrings never change in place: name.upper() returns a new string. Store it: name = name.upper().

Exercises

Exercise 1

You have name = " mOHAMMED ". Clean it and print it as Mohammed.

Exercise 2

Read a CSV line like Sara,IT,13500 and print: Sara works in IT.

Spotted a mistake on this page, or have an idea to improve the site?