Start learning free

LESSON 4 OF 66 · SQL: BEYOND THE BASICS

Clean Up Text in Python

Practice

Text typed by people is messy: spaces at the ends, capitals in odd places. SQL has text functions that tidy a value as you read it, without changing what is stored. TRIM cuts the spaces at both ends, LOWER turns every letter into lowercase, REPLACE(text, old, new) swaps one piece of text for another, SUBSTR(text, start, length) takes a slice, and || glues texts into one.

SELECT TRIM('  Mug  ') AS item,
       UPPER('cluj') AS city,
       SUBSTR('2026-05-02', 1, 7) AS month,
       REPLACE('2026-05-02', '-', '/') AS day,
       'Mug' || ' x' || '2' AS line
item | city | month | day | line
Mug | CLUJ | 2026-05 | 2026/05/02 | Mug x2

Three details matter. REPLACE tells capitals apart, so lowercase a text before you look for a piece of it. || adds nothing between the pieces: 'a' || 'b' is 'ab', so put the spaces you want inside the pieces. And a column built from an expression is named after the whole expression, so give it a short name with AS.

The hidden setup adds two customers typed in a hurry (the quotes show where each text starts and ends):

id | name             | email                | city
6  | '  Felix Braun ' | ' FELIX@example.com' | Berlin
7  | 'Gina Marin   '  | 'Gina@Example.COM  ' | Cluj

The check prints your query's rows with show(db, query), and every customer must come out tidy:

name | email | label
Ana Pop | ana@example.com | ana (Cluj)
Ben Ortiz | ben@example.com | ben (Madrid)
Chloe Ng | chloe@example.com | chloe (Cluj)
Dan Weber | dan@example.com | dan (Berlin)
Eva Rossi | eva@example.com | eva (Rome)
Felix Braun | felix@example.com | felix (Berlin)
Gina Marin | gina@example.com | gina (Cluj)
(7 rows)

Your task: db is already connected to shop.db. In query, read the customers and select three columns: name, the name trimmed; email, the email trimmed and lowercased; and label, that tidy email without '@example.com', then a space and the city in brackets.


Assignment
Follow the Coding Tutorial to build the query one line at a time: the three columns, then FROM customers, then the || line that turns the third column into label.


Hint
Functions nest, and the inner one runs first: UPPER(TRIM(city)) trims, then uppercases. Clean the email the same way before the REPLACE, or Gina's '@Example.COM' won't match. Each line of query is a Python string ending in a space, so the lines glue into one query.


STEP 1 OF 5
    Ctrl + Enter to check

    Sqlx Text in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free