Codectionary / Developer documentation / Python

f-Strings

An f-string is a string literal prefixed with f. Expressions inside braces are evaluated when that line runs and their formatted values become part of a new string. Use f-strings for readable messages that combine text and computed values.

How it works

Write f"Hello, {name}" to insert a value. The expression reads the current value at evaluation time; the resulting string does not automatically update when name changes later.

A colon introduces a format specification. :.2f displays a number with two digits after the decimal point; :03d pads an integer to three digits with zeroes; :, groups a number using commas. These control presentation and do not change the original numeric value.

Double braces {{ and }} produce literal braces. !r uses repr(), which is useful for seeing quotes and escape characters during debugging. Basic f-strings require Python 3.6; these examples avoid syntax that depends on the expression-parsing improvements in Python 3.12.

Common mistakes and boundaries

Do not use f-strings to insert untrusted values into SQL: use database parameters. Formatting also does not perform HTML escaping or shell quoting.

Formatting currency to two places is not a substitute for a decimal arithmetic and rounding policy. Keep complicated expressions outside the braces so the message is easy to read.

Try it yourself

Create a receipt line containing a product name, a quantity and a total to two decimal places. Include literal braces around a label. Change the total afterwards and check whether an already-created receipt string changes.

Syntax

f"text {expression}"

Examples

Basic Interpolation

Embedding variable values directly inside a string.

name = "John"
age = 21
print(f"{name} is {age} years old")
  1. The two names are read when the f-string is created and inserted into the sentence.
  2. Expected output: John is 21 years old

Expressions Inside f-strings

f-strings can contain any valid expression, not just plain variable names.

a = 5
b = 3
print(f"{a} + {b} = {a + b}")

items = ["apple", "banana", "cherry"]
print(f"You have {len(items)} items")

user = {"name": "Priya"}
print(f"Hello, {user['name']}!")
  1. Expressions may calculate a result, call len or look up a dictionary value. Keep those expressions short.
  2. Expected output: 5 + 3 = 8 You have 3 items Hello, Priya!

Formatting Numbers

Using format specifiers to control decimal places, padding, and thousands separators.

price = 19.5
print(f"${price:.2f}")        # $19.50

number = 7
print(f"{number:03d}")        # 007

population = 1500000
print(f"{population:,}")      # 1,500,000
  1. The format specifications change display width, decimal places and grouping without modifying the stored numbers.
  2. Expected output: $19.50 007 1,500,000

Multi-line f-strings

Combining f-strings with triple quotes for readable multi-line output.

name = "John"
role = "Developer"

profile = f"""
Name: {name}
Role: {role}
Status: Active
"""
print(profile)
  1. Triple quotes preserve line breaks. The opening and closing line breaks in this example produce blank lines around the profile.
  2. Expected output: Name: John Role: Developer Status: Active

Best practices

  • Use format specifiers like :.2f for currency and :, for thousands separators instead of manual string manipulation
  • Keep expressions inside f-strings simple - if logic gets complex, compute the value in a variable first
  • Remember f-strings require Python 3.6 or later - check your target Python version if compatibility matters

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading