Clean text so keys match
In chapter 2 you joined records with a dict lookup. A lookup only works when the key is exactly the same. " Asha " and "Asha" are different keys.
Text from other systems is often messy. It has extra spaces, mixed case, odd characters and values packed into one line.
A string is a piece of text. In Python its type is str. This chapter shows how to clean strings so equal values become the same string.
Here are the customers, and the same five names as a made-up partner app sent them:
| customer_id | name | country |
|---|---|---|
| 1 | Asha | IN |
| 2 | Ben | GB |
| 3 | Carla | US |
| 4 | Dev | None |
| 5 | Omar | IN |
| position | value as Python sees it |
|---|---|
| 0 | ' Asha ' |
| 1 | 'BEN' |
| 2 | 'carla\t' |
| 3 | 'Dev\xa0' |
| 4 | 'OMAR' |
\t is a tab. \xa0 is a non-breaking space, which looks like a normal space. OMAR uses wide letters.
customers = [
{"customer_id": 1, "name": "Asha", "country": "IN"},
{"customer_id": 2, "name": "Ben", "country": "GB"},
{"customer_id": 3, "name": "Carla", "country": "US"},
{"customer_id": 4, "name": "Dev", "country": None},
{"customer_id": 5, "name": "Omar", "country": "IN"},
]
partner_names = [" Asha ", "BEN", "carla\t", "Dev\xa0", "OMAR"]
id_by_name = {c["name"]: c["customer_id"] for c in customers}
print([id_by_name.get(name) for name in partner_names])| output |
|---|
| [None, None, None, None, None] |
All five people are in both lists, but the lookup finds none of them. By the end of this chapter, one small function finds all five.
You will learn to:
- Turn bytes into text, and know why the length can change.
- Remove spaces and fold case.
- Make look-alike characters the same, where Python can.
- Cut a line into fields.
- Find and change text with regular expressions.
- Build one key function for every join.
