Natural Language Processing · Beginner level

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

  1. Write clean(text) that lowercases, strips and collapses whitespace.
  2. Test it on five messy example messages.
  3. Apply it to the dataset with apply().
  4. 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

  1. Why keep the original text column?

    Show answer

    To compare before and after and to recover from cleaning mistakes.

  2. 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.