f-strings

Embed variables and expressions directly inside strings.

Syntaxf'Hello, {name}!'

f-strings (formatted string literals) are the modern way to build strings from values. Put an f before the opening quote, then drop variables and expressions inside { }.

Why they are great

No more clumsy + and str() — the values are inserted for you, and any expression works inside the braces.

Example

Example · python
name = 'Ada'
age = 36
print(f'{name} is {age} years old.')
print(f'Next year: {age + 1}')

price = 9.5
print(f'Total: {price:.2f}')

# Output:
# Ada is 36 years old.
# Next year: 37
# Total: 9.50

When to use it

  • A report generator inserts calculated totals and user names directly into a formatted string.
  • A logging function embeds the current timestamp and error level into each log line.
  • An API builds a personalised error message by embedding the offending field name in the response.

More examples

Basic f-string interpolation

Inserts variable values into a string literal using curly brace placeholders.

Example · python
name = 'Ada'
age = 35
print(f'{name} is {age} years old.')

# Output:
# Ada is 35 years old.

Expressions inside f-strings

Evaluates an arithmetic expression and formats the float to 2 decimal places inside the f-string.

Example · python
price = 49.99
quantity = 3
print(f'Total: ${price * quantity:.2f}')

# Output:
# Total: $149.97

Alignment and padding

Uses format specifiers for left-aligned text and right-aligned, fixed-decimal numbers.

Example · python
items = [('Apple', 1.20), ('Banana', 0.50), ('Cherry', 3.00)]
for name, price in items:
    print(f'{name:<10} ${price:>5.2f}')

# Output:
# Apple      $ 1.20
# Banana     $ 0.50
# Cherry     $ 3.00

Discussion

  • Be the first to comment on this lesson.