Beginner level · Module 3: Text Cleaning and Preprocessing · Lesson 1 of 3
String Methods for Cleaning Text
Learners use lower(), strip(), replace() and split() to fix common problems in messages and write their first reusable cleaning function.
In this lesson you will
- Apply Python string methods to clean text
- Write a reusable cleaning function
Key concepts
lower()strip()replace()split() and join()functions
The lesson
Python strings have built-in methods for simple cleaning. lower() makes 'URGENT' and 'urgent' the same; strip() removes spaces at the ends; replace() swaps one piece of text for another; ' '.join(text.split()) collapses repeated spaces and line breaks into single spaces.
Wrapping these steps in a function, def clean(text): ..., means every message is cleaned the same way. Consistency matters more than perfection: the training data and the new messages must go through exactly the same steps.
Use pandas to apply the function to a whole column: df['clean'] = df['text'].apply(clean). Keep the original column, so you can always compare before and after.
Step by step
- Write clean(text) that lowercases, strips and collapses whitespace.
- Test it on five messy example messages.
- Apply it to the dataset with apply().
- Print five before/after pairs.
Practice activity
Write and test a basic cleaning function on the project dataset.
Expected result: A function that produces consistent, readable cleaned text, with before/after examples.
Check your understanding
-
Why keep the original text column?
Show answer
To compare before and after and to recover from cleaning mistakes.
-
What does ' '.join(text.split()) do?
Show answer
It collapses repeated spaces, tabs and line breaks into single spaces.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.