Python Foundations·Shape the data

Strings and formatting

Clean, split and format text — the data type every program touches.

Beginner 12 min read Lesson 9 of 480 Challenge included
What you will be able to do
  • Normalise text with string methods
  • Split and join safely
  • Format numbers inside f-strings

Text arrives messy: extra spaces, mixed case and inconsistent separators. String methods return new values, so chain them and keep the original intact.

strings.pyPython
name = "  Ada Lovelace  "
clean = name.strip()
print(clean.lower())
print(clean.upper())

words = clean.split()
print(words)
print("-".join(words))

price = 24.5
quantity = 3
print(f"Total: {price * quantity:.2f}")

title = "python foundations"
slug = title.lower().replace(" ", "-")
print(slug)
MethodResult
.strip()Remove whitespace from both ends
.lower() / .upper()Change case
.replace(old, new)Swap every occurrence
.split(sep)Break into a list
.join(items)Combine an iterable into text
.startswith(prefix)Check the beginning
  • Strings are immutable: methods return a new string.
  • split() without arguments collapses runs of whitespace.
  • join() is called on the separator, not on the list.
Your turn

Build a URL slug

Easy

Turn the title into a slug: trim it, lowercase it and join the remaining words with hyphens.

PYTHON · starter
title = "  Learn Python Fast  "
# your code here
Check your understanding before moving on.
Knowledge checkQuestion 1

What does " PYTHON ".strip().lower() return?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 9 of 480 · 0% of course