String methods

Clean up a little text

Lesson 8 of 20 · 8 min · Module 3: Working with collections

Text rarely arrives in exactly the shape your program needs. String methods let you clean it up without rewriting the original value.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Split and rejoin text
  • Distinguish whitespace splitting from a literal separator
  • Keep normalization rules explicit

The idea

split() without an argument separates words on whitespace and ignores repeated whitespace. " ".join(words) joins words with one space. title() capitalizes words.

text = "  small   steps  "
print(" ".join(text.split())) # small steps

01Let split handle whitespace

With no separator, split treats runs of spaces, tabs, and line breaks as separators. An empty or whitespace-only string produces an empty list.

02Use title casing for this exercise

title provides a predictable demonstration of a string method. Real people’s names have varied capitalization rules, so production forms should generally respect the spelling a person provides.

Your turn

Define clean_name(text) to remove extra whitespace and title-case the words. For " aLEX mORGAN ", return "Alex Morgan".

What the checks look for

  • Normalizes spaces and capitalization
  • Handles tabs and line breaks
  • Handles empty input
Try it in the editor →

Take this with you

Choose a normalization rule to fit the data, rather than changing text blindly.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →