CodeBlanks Logo Icon CodeBlanks

f-string formatting

Learn number formatting with f"{x:.2f}".

f-strings

An f-string starts with the f prefix and embeds an expression in curly braces {}:

name = "Ayşe"
age = 30
print(f"Merhaba, {name}!")
# Merhaba, Ayşe!
print(f"Yaş: {age + 1}")
# Yaş: 31

The expression inside the f-string is evaluated and its result is embedded in the string. Variables, arithmetic, function calls — any expression works.

Python 3.12 also supports nested f-strings and multi-line f-strings.

Format specifiers

After the colon : inside the curly braces comes a format specifier:

score = 95.567
print(f"{score:.1f}")   # 95.6
print(f"{score:>10}")    #     95.567
print(f"{42:0>5}")       # 00042

.1f means one decimal, >10 means right-align width 10, 0>5 means zero-fill width 5. These specifiers align output and format numbers.

Format specifiers are valuable for table and report output.

Practice Print score with f-string

Assign "Ayşe" to name. Assign 95.5 to score. Then write print(f"{name}: {score:.1f}").

Starter code

main.py
# assign name and score
# format and print with f-string

Sample solution

main.py
name = "Ayşe"
score = 95.5
print(f"{name}: {score:.1f}")

Expected output

Ayşe: 95.5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which prints 3.142? (x = 3.14159)

  • f'{x:.0f}'
  • f'{x:.1f}'
  • f'{x:.3f}' Correct answer
  • f'{x:.2f}'

Explanation: :.3f shows three decimal places: 3.142.

2 Match format specifiers

Term Meaning
:.2f Two decimals
:>10 Right-align
:0>5 Zero-fill
:.0f No decimals

3 Complete the f-string format

Question
result = f"Score: {score:____}"
Answer
result = f"Score: {score:.1f}"

Explanation: {score:.1f} shows one decimal place.

All lessons in Beginner