Skip to contentSkip to navigation

Module 03 · Lesson 04

String Methods & Text Sanitization

Clean and reshape text with string methods: change case, strip spaces, split into words and join them back, find and replace, and test what a string contains.

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • Change the case
  • Strip, split and join
  • Find and replace
  • Chain methods

Tools built into every string

Every string comes with methods: commands you call with a dot, like `name.upper()`. Each gives back a new string.

  • Case

    upper(), lower() and title() change capital letters.

  • Tidy

    strip() removes spaces from both ends, so " Sam " becomes "Sam".

  • Split and join

    split() breaks text into a list of words. ", ".join(words) glues them back together.

  • Find and replace

    find(), count() and replace() search inside the text.

  • Test

    isdigit(), isalpha() and startswith() answer True or False questions about the text.

Tidy text everywhere

People type messy text. Programs tidy it up before using it.

  • Sign-inEmails are stripped and made lower case, so Ana@Mail.com still matches.
  • HashtagsA title is split into words and joined with no spaces to make a tag.
  • File namesSpaces are replaced with underscores so the name is safe to save.
  • Chat filtersMessages are lowered and searched for words that should be hidden.

Two methods in a row

Each method hands back new text, so the next method can work on it. Tap each part to see its job.

Part 1 of 3

Tap any part of the code below, or press Next.1 of 3 explored

messy text:A space at each end and two capital letters.

Prints hi there

Clean and change text

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Case

Each method gives back a new string. The original stays the same.

Your turn: Use swapcase() and see what it does.

Python
msg = "hello World"
print(msg.upper())
print(msg.lower())
print(msg.title())
print(msg)
Output
Press Run to see what it prints.

Watch messy text get tidy

Press Step to run one line at a time. Each line makes a new, tidier value.

Ready. Press Step to run the first line.

  1. raw = " tea, COFFEE, juice "
  2. clean = raw.strip().lower()
  3. drinks = clean.split(", ")
  4. menu = " | ".join(drinks)
  5. print(menu)
  6. print(drinks[1].title())

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.How many?

print("banana".count("a"))

0 of 6 answered

Common method misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Tools that come with every string

A method is a function that belongs to a value. You call it with a dot after the value: text.upper(). Strings come with dozens of methods. This lesson covers the ones you will use every week.

The rule from the last lesson matters more than any single method: strings are immutable, so every method returns a new string. The original is never changed. If you want to keep the result, store it, often under the same name.

Try it 1: edit me, then Run
name = "  ada lovelace "
name.strip()             # makes a cleaned copy, then throws it away
print(repr(name))        # '  ada lovelace '
name = name.strip()      # keep the cleaned copy
print(repr(name))        # 'ada lovelace'
Output
Press Run to see what it prints.

repr() shows a string with its quotes, which makes leading and trailing spaces visible while you debug.

Changing case

Try it 2: edit me, then Run
word = "pYthOn rocks"
print(word.lower())       # python rocks
print(word.upper())       # PYTHON ROCKS
print(word.title())       # Python Rocks
print(word.capitalize())  # Python rocks
Output
Press Run to see what it prints.

lower() is the standard way to compare text without caring about case: answer.lower() == "yes" accepts Yes, YES and yes. title() capitalises the first letter of every word, which is handy for names, though it gets some wrong, such as McDonald.

Removing spaces

strip() removes whitespace (spaces, tabs and new lines) from both ends, never from the middle. lstrip() and rstrip() do only the left or right end. Give them a string of characters to remove something else: "--title--".strip("-") is title. Stripping is the first thing to do with almost any typed input.

Splitting and joining

split() breaks a string into a list of pieces. With no argument it splits on any run of whitespace and ignores spaces at the ends, which makes it perfect for counting words. With an argument it splits exactly at that separator.

Try it 3: edit me, then Run
sentence = "  the quick   brown fox "
print(sentence.split())          # ['the', 'quick', 'brown', 'fox']
row = "Ana,82,Leeds"
print(row.split(","))            # ['Ana', '82', 'Leeds']
print("a-b-c".split("-", 1))     # ['a', 'b-c'], at most one split
Output
Press Run to see what it prints.

join() is the opposite. It is called on the separator and given a list of strings, and it glues them together with the separator between each pair.

Try it 4: edit me, then Run
words = ["red", "green", "blue"]
print(", ".join(words))          # red, green, blue
print("".join(["a", "b", "c"]))  # abc
Output
Press Run to see what it prints.

The order looks backwards at first, separator.join(items), but it reads well once you say it aloud: "comma-space, join these words". Every item must be a string; joining a list of numbers raises TypeError, so convert them first. Splitting on one separator and joining with another is a neat way to reformat text: "-".join("2024 06 15".split()) gives 2024-06-15.

Finding and replacing

Try it 5: edit me, then Run
text = "banana bandana"
print(text.count("an"))          # 4
print(text.find("nan"))          # 2, the first position
print(text.find("xyz"))          # -1, not found
print(text.replace("an", "AN"))  # bANANa bANdANa
print(text.startswith("ban"), text.endswith("na"))
Output
Press Run to see what it prints.

find() returns the index where the text first appears, or -1 if it does not appear. index() does the same but raises ValueError when the text is missing, which is better when absence really is an error. replace(old, new) swaps every occurrence; an optional third argument limits how many. For a simple yes or no, in is clearer than find(): write "nan" in text.

startswith() and endswith() check the beginning and end, and both accept a tuple of options: file_name.endswith((".jpg", ".png")).

Testing what a string contains

A family of methods starting with is answer questions about every character and return True or False.

  • isdigit(): only the digits 0 to 9, so it is a quick check before int().
  • isalpha(): only letters.
  • isalnum(): only letters and digits.
  • isspace(), isupper(), islower(): only whitespace, only uppercase or only lowercase letters.

Note that "-5".isdigit() and "2.5".isdigit() are both False, because a minus sign and a point are not digits. An empty string returns False for all of them.

Chaining methods

Because each method returns a new string, you can call another method on the result straight away. This is called chaining, and it reads from left to right.

Try it 6: edit me, then Run
raw = "  My Holiday Photo.JPG "
clean = raw.strip().lower().replace(" ", "_")
print(clean)                     # my_holiday_photo.jpg
Output
Press Run to see what it prints.

Chains of two or three methods are easy to read. When a chain grows longer, split it into steps with named variables so each step can be checked on its own.

Methods and f-strings together

Methods are often used inside f-string braces: f"Welcome, {name.strip().title()}!" cleans and formats in one place. Keep such expressions short. If the same cleaned value is used more than once, clean it once into a variable, which is both faster and easier to read.

Finding the right method

You do not need to memorise every method. In the editor, help(str) lists them all, and the Reference section of this site has examples for the common ones. When you need to do something to text, it is worth checking whether a method already does it before writing a loop.

Syntax

The general shape of the statements in this lesson.

syntax.py
s.lower()  s.upper()  s.title()  s.capitalize()
s.strip()  s.lstrip()  s.rstrip()  s.strip("-")
s.split()  s.split(",")  ", ".join(items)
s.replace("a", "b")  s.count("x")  s.find("x")  s.index("x")
s.startswith("ab")  s.endswith((".jpg", ".png"))
s.isdigit()  s.isalpha()  s.isalnum()
s.strip().lower()          # chaining
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Tidy a list of names

Beginner

A sign-up sheet has names typed with stray spaces and random capitals, separated by commas. Turn it into a clean, title-cased list, sorted, and print it as one line.

Python
sheet = "  ada lovelace, ALAN turing ,grace HOPPER  "
names = []
for part in sheet.split(","):
    names.append(part.strip().title())
print(names)
print(" | ".join(sorted(names)))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

split(",") cuts the sheet into three pieces, each still messy. Inside the loop, strip() removes the spaces and title() fixes the capitals, and the cleaned name is appended to a new list. join() then builds one line from the sorted names.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Calling a method and not keeping the result

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
email = " Ana@Mail.com "
email.strip().lower()
print(email)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints the original text with its spaces and capitals

Write this instead

email = " Ana@Mail.com "
email = email.strip().lower()
print(email)

Why it happens

Methods return a new string. The cleaned copy was made and then thrown away.

In the real world

Where this shows up in software people use every day.

  1. Making a web address slug

    Publishing

    A blog turns each article title into the readable part of its web address, called a slug, so How to Bake Bread becomes how-to-bake-bread.

    Why Python fits

    Lowercasing and keeping only letters, digits and spaces removes the punctuation. split() with no argument collapses every run of spaces, and joining with dashes gives a slug that is safe in a web address.

    Python
    title = "  How to Bake   Bread: A Beginner's Guide "
    cleaned = ""
    for ch in title.lower():
        if ch.isalnum() or ch == " ":
            cleaned += ch
    slug = "-".join(cleaned.split())
    print(slug)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

What is the difference between split() and split(" ")?

split() treats any run of whitespace as one separator and ignores the ends. split(" ") splits at every single space, so two spaces in a row give an empty string in the list.

How do I remove all spaces, not just at the ends?

Use text.replace(" ", ""), or "".join(text.split()) to remove every kind of whitespace.

Is isdigit() enough to check for a number?

Only for whole, non-negative numbers. Negative numbers and decimals need other checks, which the error-handling lessons in a later course cover.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.