String methods and f-strings · Python from Zero
How do you change, search and format text easily?
Course contentsWhy you need it
Real input is messy: extra spaces, random capital letters. And output should read nicely: "Ada scored 95 points", not a jumble of commas and +. Strings come with built-in methods for cleaning and searching, and f-strings make formatting painless.
The intuition
A method is a function that belongs to a value. You call it with a dot: value.method().
| Method | What it does | Example |
|---|---|---|
.upper() / .lower() | change case | "Hi".upper() → "HI" |
.strip() | remove spaces at both ends | " hi ".strip() → "hi" |
.replace(a, b) | replace every a with b | "cat".replace("c", "b") → "bat" |
.count(x) | how many times x appears | "banana".count("a") → 3 |
Methods return a new string; the original doesn't change (strings are immutable).
"an" in "banana" asks "does it contain...?" and gives True or False.
An f-string starts with f and puts values inside { }: f"{name} is {age}". Any expression works in the braces: f"{age + 1}".
Definition
Method
A method is a function attached to a value, called with dot notation such as text.upper().
f-string
An f-string is a string literal prefixed with f in which expressions inside braces are evaluated and inserted.
Examples
Cleaning messy input
Try it yourselfMethods can be chained: each one works on the result of the previous.
msg = " Hello World "
clean = msg.strip().lower()
print(clean)
print(clean.count("o"), "world" in clean)
print(msg)- L2strip() removes the outer spaces, then lower() makes it lowercase.
clean = 'hello world' - L4Two o's; and "world" is inside.
2 True - L5msg itself never changed: methods return new strings.
Formatting with f-strings
Try it yourselfCompare the two print lines: same output, but the f-string is easier to read.
name = "Ada"
score = 95
print(name + " scored " + str(score) + " points")
print(f"{name} scored {score} points")
print(f"Next time: {score + 5}")- L3With +, numbers must be converted with str() first.
- L4With an f-string, {score} is inserted automatically.
- L5Any expression works inside the braces.
Next time: 100
Common mistakes
Forgetting the f
"{name}" without the f prints the braces literally. Write f"{name}".
Expecting the original to change
name.upper() alone does nothing visible. Store or print the result: name = name.upper().
Quick quiz
1. What does this print?
print("banana".replace("a", "o"))Show the answer
Answer: A
replace changes every "a".
2. What does this print?
x = 3
print(f"x={x * 2}")Show the answer
Answer: A
The expression in braces is calculated: 3 × 2 = 6.
Practice
3 exercises in three steps: predict what a program prints, change a program to meet a new requirement, then write one from scratch. Your code runs in the browser and is checked the moment you submit.
- PredictMethods in action
Type exactly what this program prints.
- ModifyTidy greeting
Users type names with stray spaces and odd capitals. Clean the name with
.strip()and.capitalize()(first letter upper, the rest lower), and print the greeting with an f-string:Hello, Ada! - WriteShout and count
Read a word. Print it in capitals on the first line, and on the second line how many times the letter a appears in it, counting both a and A.
Practise this lesson
Open the interactive lesson to edit and run these examples and solve the exercises with instant feedback. Free to start, no sign-up.
Interactive lessons open in order. If you have not done the earlier ones yet, you start at the course map.
Terms in this lesson
| Term | Chinese | Definition |
|---|---|---|
| Method | 方法 | A function attached to a value, called with a dot. |
| f-string | f-string 格式化字符串 | A string starting with f whose {expressions} are evaluated and inserted. |
| Immutable | 不可变 | Describes values, like strings, that cannot be changed after they are created. |
| in | in 成员运算 | An operator that checks whether a value is contained in another, giving True or False. |