How to Use f-strings in Python

What you’ll build or solve

You’ll format text using f-strings so your output stays readable and your values show up correctly.

When this approach works best

This approach works best when you:

  • Build user-facing messages, logs, or CLI output that includes values like names, totals, or IDs.
  • Format numbers, money, and percentages with consistent rounding and alignment.
  • Debug by printing variables with context, like total=123.45 instead of just 123.45.

Avoid this approach when:

  • You need to support Python older than 3.6. In that case, use str.format() or string concatenation.

Prerequisites

  • Python 3.6+ installed
  • You know what variables are
  • You know what strings are
  • You can run a .py file or use the Python REPL

Step-by-step instructions

1) Create your first f-string with variables

An f-string is a string literal that starts with f and contains {} placeholders.

name="Ada"
city="Los Angeles"

message=f"Hi{name}, welcome to{city}!"
print(message)

What to look for:

  • The f must be right before the opening quote.
  • Placeholders must use curly braces {}.

2) Put expressions inside {}

You can run simple expressions inside the braces, not just variable names.

items=3
price=4.5

total=items*price
print(f"Total:{items} ×{price} ={total}")

You can also call functions:

username="  srđan  "
print(f"Normalized:{username.strip().lower()}")

Anything inside {} is evaluated as Python code.


3) Control formatting with format specifiers

After a value, add : and a format specifier to control how it displays.

Option A (most common): round floats with .2f

score=0.91321
print(f"Score:{score:.2f}")# 0.91

Useful specifiers:

  • Thousands separators: :,
  • Percent: .2%
  • Padding and alignment: <, >, ^ with a width
count=12000
ratio=0.267

print(f"Users:{count:,}")
print(f"Conversion:{ratio:.1%}")
print(f"[{count:>10}]")# right-align in a 10-char field

What to look for:

Formatting goes inside the braces, after a colon, like {value:.2f}.


4) Build multi-line strings cleanly

Use triple quotes for multi-line f-strings. This works well for templates and longer messages.

first="Mina"
last="Kovač"
points=42

text=f"""Profile
Name:{first}{last}
Points:{points}
"""
print(text)

If you want to avoid extra indentation in the output, build lines and join them:

lines= [
f"Name:{first}{last}",
f"Points:{points}",
]

print("\n".join(lines))

5) Escape braces and quotes

If your output needs literal braces, double them:

key="user_id"
print(f"Use JSON like this: {{\"{key}\": 123}}")

If your f-string contains quotes, pick the opposite quote style:

title='Beginner "Python" Course'
print(f'Title:{title}')

6) Use f-strings for clearer debugging output

Label values so the output explains itself:

items= ["apple","pear"]
total=12.5

print(f"items:{items}")
print(f"total:{total}")

If you’re on Python 3.8+, you can use the {name=} shortcut:

items= ["apple","pear"]
total=12.5

print(f"{items=}")
print(f"{total=}")

What to look for:

{name=} prints the variable name and its value. This requires Python 3.8+.


Examples you can copy

1) Friendly message with a timestamp

fromdatetimeimportdatetime

name="Noah"
now=datetime.now()

print(f"Hi{name}! Time:{now:%Y-%m-%d %H:%M}")

2) Receipt-style output with alignment

product="Notebook"
qty=3
unit_price=2.5
total=qty*unit_price

print(f"{'Item':<12}{'Qty':>5}{'Price':>10}")
print(f"{product:<12}{qty:>5}{unit_price:>10.2f}")
print(f"{'Total':<12}{'':>5}{total:>10.2f}")

3) Status line for logs

user_id=1042
errors=2
duration=1.9347
ok=errors==0

status="ok"ifokelse"error"
print(f"user_id={user_id} status={status} errors={errors} duration={duration:.3f}s")

Common mistakes and how to fix them

Mistake 1: Forgetting the f prefix

You might write:

name="Luka"
print("Hello {name}")

Why it breaks:

Without the f, Python treats {name} as plain text.

Correct approach:

name="Luka"
print(f"Hello{name}")

Mistake 2: Mismatched braces or quotes

You might write:

value=10
print(f"Value:{value")

Why it breaks:

A missing } (or an extra quote) causes a syntax error.

Correct approach:

value=10
print(f"Value:{value}")

Mistake 3: Forgetting to escape literal {}

You might write:

print(f"Set is{1,2,3}")

Why it breaks:

Python treats {...} as an f-string expression, not literal braces.

Correct approach:

print(f"Set is {{1, 2, 3}}")

Troubleshooting

If you see SyntaxError: f-string: expecting '}', check for a missing } or a { that should be {{.

If you see SyntaxError: invalid syntax on the f-string line, check for unclosed quotes inside the string.

If you see NameError inside {}, the variable is not defined. Check spelling or define it earlier.

If f-strings do not work at all, confirm you are running Python 3.6+. If needed, try python3 instead of python.

If {name=} does not work, you are likely on Python 3.7 or older. Use explicit labels like f"total: {total}".


Quick recap

  • Prefix the string with f and put values inside {}.
  • Use expressions inside braces, like {qty * price}.
  • Add format specifiers with :, like {total:.2f} or {count:,}.
  • Use triple quotes for multi-line templates.
  • Escape literal braces with {{ and }}.
  • For debugging, label values, and use {name=} on Python 3.8+.