Python · Stage 2 – Doing Things with Values · Lesson 18 of 50

Formatting Output with f-Strings

Place a variable value inside a readable piece of text.

name = "Maya"
message = f"Hello, {name}!"
Line-by-line explanation
  1. The first line stores a name.
  2. The f marks the second string as an f-string.
  3. {name} is replaced by the value in name.
  4. message stores Hello, Maya!.

Tiny Practice

Create the message “You have 3 lives” using the variable.

Starter template

lives = 3
message = CHANGE_ME
print(message)
Line-by-line explanation
  1. The first line stores the number.
  2. The second line must create an f-string.
  3. The last line displays it.
Hint
  1. Start the string with f.
  2. Put lives in curly braces.
  3. Keep the other words inside quotes.
Show Solution
lives = 3
message = f"You have {lives} lives"
print(message)
Line-by-line explanation
  1. The first line stores 3.
  2. The f-string inserts that value.
  3. The output is You have 3 lives.