Everyone Can Learn Program
中文 Start learning
Course 2 · Python BasicsLesson 6 of 14Free to read

String methods and f-strings · Python from Zero

How do you change, search and format text easily?

Course contents

Why 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().

MethodWhat it doesExample
.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 yourself

Methods 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)
Step by step
  1. L2strip() removes the outer spaces, then lower() makes it lowercase.clean = 'hello world'
  2. L4Two o's; and "world" is inside.2 True
  3. L5msg itself never changed: methods return new strings.

Formatting with f-strings

Try it yourself

Compare 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}")
Step by step
  1. L3With +, numbers must be converted with str() first.
  2. L4With an f-string, {score} is inserted automatically.
  3. 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"))
  1. A
    bonono
  2. B
    bonana
  3. C
    banana
Show the answer

Answer: A

replace changes every "a".

2. What does this print?

x = 3
print(f"x={x * 2}")
  1. A
    x=6
  2. B
    x=3 * 2
  3. C
    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.

  1. PredictMethods in action

    Type exactly what this program prints.

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

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

TermChineseDefinition
Method方法A function attached to a value, called with a dot.
f-stringf-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.
inin 成员运算An operator that checks whether a value is contained in another, giving True or False.