ZetCode

Python f-string

last modified November 16, 2026 Python 3.15

In this article we show how to format strings in Python with f-strings.

A Python f-string (formatted string literal) is a string literal prefixed with f or F that contains replacement fields in curly braces. Each field holds a Python expression, which is evaluated at run time; its result is formatted and inserted into the string. F-strings were introduced in Python 3.6 (PEP 498) and are the preferred way of building strings from values in modern Python. They are shorter and easier to read than the % operator and the str.format method, and they are also faster, because the formatting is compiled into the bytecode.

A replacement field has the form {expression=!conversion:format_spec}, where everything after the expression is optional. The = sign prints the expression text together with its value, the conversion (!s, !r, or !a) chooses between str, repr, and ascii, and the format specifier after the colon controls width, alignment, precision, and other details.

first.py
name = 'Alice'
age = 30

print(f'Hello, my name is {name} and I am {age} years old.')

Python replaces {name} and {age} with the values of the two variables. The integer is converted to a string automatically.

$ python first.py
Hello, my name is Alice and I am 30 years old.

Python string formatting

Python has three built-in ways of formatting strings. The example compares the oldest %-style formatting, the str.format method, and the f-string.

formatting.py
name = 'Peter'
age = 23

print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print(f'{name} is {age} years old')

All three lines produce the same text.

print('%s is %d years old' % (name, age))

This is the oldest option. It uses the % operator and C-like conversion specifiers such as %s and %d. The values are passed separately in a tuple.

print('{} is {} years old'.format(name, age))

The str.format method, available since Python 2.6 and 3.0, uses {} placeholders and the format specification mini-language. The values are still passed separately as arguments.

print(f'{name} is {age} years old')

The f-string uses the same mini-language as str.format, but the values are written directly inside the placeholders, so the text and the data are read together.

$ python formatting.py
Peter is 23 years old
Peter is 23 years old
Peter is 23 years old

Expressions

Any valid Python expression can be placed inside the curly braces: arithmetic, method and function calls, conditional expressions, comprehensions, or generator expressions.

expressions.py
bags = 3
apples_in_bag = 12
words = ['sky', 'forest', 'cup']
temp = -4

print(f'There are {bags * apples_in_bag} apples in total')
print(f'The longest word is {max(words, key=len).upper()}')
print(f'It is {"freezing" if temp < 0 else "fine"} outside')
print(f'Word lengths: {[len(w) for w in words]}')
print(f'Total length: {sum(len(w) for w in words)}')

The expressions are evaluated from left to right in the scope where the f-string appears, so they can use local variables and imported names.

print(f'It is {"freezing" if temp < 0 else "fine"} outside')

A conditional expression chooses one of two strings. Keep such fields short; when the logic grows, compute the value in a variable first and put only the variable in the f-string.

$ python expressions.py
There are 36 apples in total
The longest word is FOREST
It is freezing outside
Word lengths: [3, 6, 3]
Total length: 12

Dictionaries and quotes

Dictionary items are accessed with the usual subscript syntax. Since Python 3.12 (PEP 701), the expression may use the same kind of quotes as the enclosing string.

dicts.py
user = {'name': 'John Doe', 'occupation': 'gardener'}

print(f"{user['name']} is a {user['occupation']}")
print(f'{user['name']} is a {user['occupation']}')

The first f-string uses double quotes outside and single quotes for the keys. This is the only form that works in Python 3.11 and older. The second f-string reuses single quotes inside the replacement fields, which is allowed since Python 3.12, because the expression part is now parsed by the regular Python parser.

$ python dicts.py
John Doe is a gardener
John Doe is a gardener

The = debug specifier

Python 3.8 added the self-documenting expression. With an equals sign after the expression, the f-string prints the expression text, the equals sign, and the value. Whitespace around the = is preserved in the output.

debug_expr.py
import math

x = 0.8
name = 'Lucia'

print(f'{x = }')
print(f'{math.cos(x) = }')
print(f'{math.cos(x) = :.4f}')
print(f'{x*2=}')
print(f'{name = }')
print(f'{name = !s}')

The = specifier is handy for quick debugging and logging of intermediate values.

print(f'{math.cos(x) = :.4f}')

A format specifier can follow the equals sign. The value is then formatted with that specifier instead of being shown with repr.

print(f'{name = }')
print(f'{name = !s}')

Without a format specifier, = uses repr by default, so strings appear in quotes. The !s conversion switches to str.

$ python debug_expr.py
x = 0.8
math.cos(x) = 0.6967067093471654
math.cos(x) = 0.6967
x*2=1.6
name = 'Lucia'
name = Lucia

Conversions

The !s, !r, and !a conversions call str, repr, and ascii on the value before it is formatted.

conversions.py
name = 'Zoë'
path = 'C:\\Users\\zoe'

print(f'{name!s}')
print(f'{name!r}')
print(f'{name!a}')
print(f'{path}')
print(f'{path!r}')
print(f'{name!r:>10}|')

The !r conversion shows the string in quotes, with the backslashes escaped, as it would be written in source code. The !a conversion also escapes non-ASCII characters such as ë.

print(f'{name!r:>10}|')

A conversion comes before the format specifier. Here the repr of the string, including its quotes, is right-aligned in a field of ten characters.

$ python conversions.py
Zoë
'Zoë'
'Zo\xeb'
C:\Users\zoe
'C:\\Users\\zoe'
     'Zoë'|

Multiline f-strings

Triple-quoted f-strings span multiple lines. Long single-line messages can be split into several f-strings that are joined by implicit string literal concatenation.

multiline.py
name = 'John Doe'
occupation = 'gardener'
age = 34

msg = f'''name: {name}
age: {age}
occupation: {occupation}'''

print(msg)

line = (
    f'{name} is {age} years old '
    f'and works as a {occupation}'
)

print(line)

The triple-quoted f-string keeps its newlines. The second message is written as two adjacent f-strings inside parentheses; Python joins them into one string at compile time. Each part needs its own f prefix.

$ python multiline.py
name: John Doe
age: 34
occupation: gardener
John Doe is 34 years old and works as a gardener

Objects: __str__ and __repr__

When an object appears in an f-string, Python calls its __format__ method, which for most classes falls back to str. The !r conversion and the = specifier use repr instead.

str_repr.py
class User:
    def __init__(self, name, occupation):
        self.name = name
        self.occupation = occupation

    def __str__(self):
        return f'{self.name} is a {self.occupation}'

    def __repr__(self):
        return f'User({self.name!r}, {self.occupation!r})'


u = User('John Doe', 'gardener')

print(f'{u}')
print(f'{u!r}')
print(f'{u = }')

The __str__ method returns a readable description for users, while __repr__ returns an unambiguous representation for developers. The !r conversions inside __repr__ put the attribute values in quotes.

$ python str_repr.py
John Doe is a gardener
User('John Doe', 'gardener')
u = User('John Doe', 'gardener')

The __format__ method

A class can define __format__ to interpret its own format specifiers. The method receives the text after the colon and returns the formatted string.

custom_format.py
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def __format__(self, spec):
        unit = 'C'
        if spec and spec[-1] in 'CFK':
            spec, unit = spec[:-1], spec[-1]

        match unit:
            case 'C':
                value, symbol = self.celsius, '°C'
            case 'F':
                value, symbol = self.celsius * 9 / 5 + 32, '°F'
            case 'K':
                value, symbol = self.celsius + 273.15, 'K'

        return f'{value:{spec or ".1f"}} {symbol}'


t = Temperature(21.5)

print(f'{t}')
print(f'{t:F}')
print(f'{t:.2fK}')
print(f'[{t:>6.0fC}]')

The Temperature class accepts an optional unit letter at the end of the specifier. The rest of the specifier is passed on to the float formatting of the converted value; without one, the value is shown with one decimal place.

return f'{value:{spec or ".1f"}} {symbol}'

The format specifier itself contains a replacement field. The inner {spec or ".1f"} is evaluated first, and its result becomes the specifier for value.

$ python custom_format.py
21.5 °C
70.7 °F
294.65 K
[    22 °C]

Escaping characters

Literal curly braces are written by doubling them. Backslash escape sequences work in the literal part of an f-string as in any other string, and since Python 3.12 they are also allowed inside the expressions.

escaping.py
words = ['sky', 'cup', 'war']

print(f'Python uses {{}} to evaluate expressions in f-strings')
print(f'{{{len(words)}}} words')
print(f'This was a \'great\' film')
print(f'Words:\n{'\n'.join(words)}')
print(f'Tab-separated: {'\t'.join(words)}')

The {{ and }} sequences produce single braces.

print(f'{{{len(words)}}} words')

Three braces on each side produce a literal brace around the value of the expression: the outer pair is an escaped brace, the inner pair is a replacement field.

print(f'Words:\n{'\n'.join(words)}')

The '\n' separator inside the replacement field raised a SyntaxError before Python 3.12; older code had to store it in a variable first.

$ python escaping.py
Python uses {} to evaluate expressions in f-strings
{3} words
This was a 'great' film
Words:
sky
cup
war
Tab-separated: sky	cup	war

Formatting date and time

The datetime, date, and time types implement __format__ by passing the specifier to strftime, so the usual % directives can be written directly after the colon.

datetimes.py
from datetime import datetime

dt = datetime(2026, 11, 16, 14, 35, 9)

print(f'{dt}')
print(f'{dt:%Y-%m-%d %H:%M}')
print(f'{dt:%d.%m.%Y}')
print(f'{dt:%A, %B %d}')
print(f'{dt:%a %b %d}')
print(f'Day of the year: {dt:%j}')
print(f'Week day number: {dt:%w}')
print(f'{dt.date() = !s}')

The example formats a fixed point in time. Without a specifier the datetime is printed in ISO-like format. The %A and %B directives print the full day and month names, %a and %b their abbreviations, %j the day of the year, and %w the weekday as a number, where Sunday is 0. The datetime formatting article covers the directives in detail.

$ python datetimes.py
2026-11-16 14:35:09
2026-11-16 14:35
16.11.2026
Monday, November 16
Mon Nov 16
Day of the year: 320
Week day number: 1
dt.date() = 2026-11-16

Nested replacement fields

The format specifier may itself contain replacement fields. This makes it possible to choose the width, precision, alignment, or a whole date format at run time.

nested_spec.py
from datetime import date

value = 123.456789
width = 12
precision = 3

print(f'|{value:{width}.{precision}f}|')

for prec in range(4):
    print(f'{value:.{prec}f}')

d = date(2026, 3, 16)
formats = ['%d.%m.%y', '%y/%m/%d', '%B %d, %Y']

for fmt in formats:
    print(f'{d:{fmt}}')

align = '^'
print(f'|{"center":{align}{width}}|')

In {value:{width}.{precision}f}, the inner fields are evaluated first and give the specifier 12.3f.

for prec in range(4):
    print(f'{value:.{prec}f}')

The loop prints the same number with zero to three decimal places.

for fmt in formats:
    print(f'{d:{fmt}}')

Whole strftime formats can be stored in variables too.

$ python nested_spec.py
|     123.457|
123
123.5
123.46
123.457
16.03.26
26/03/16
March 16, 2026
|   center   |

Formatting floats

The presentation type at the end of the specifier controls how a float is shown: f for fixed-point notation, e or E for scientific notation, g for the general format, and % for percentages. The number after the dot sets the precision.

floats.py
val = 12.3
big = 1234567.891
tiny = 0.000123

print(f'{val:.2f}')
print(f'{val:.5f}')
print(f'{val:.0f}')
print(f'{big:e}')
print(f'{big:.2E}')
print(f'{big:g} {tiny:g} {val:g}')
print(f'{1/7:.2%}')
print(f'{2.5:.0f} {3.5:.0f}')

The .2f specifier prints two decimal places, .0f none. The g type switches between fixed-point and scientific notation depending on the magnitude, and it drops trailing zeros; its default precision is six significant digits. The % type multiplies the value by 100 and appends a percent sign.

print(f'{2.5:.0f} {3.5:.0f}')

Rounding uses round-half-to-even, so 2.5 becomes 2 and 3.5 becomes 4. For decimal rounding rules of money values, use the decimal module.

$ python floats.py
12.30
12.30000
12
1.234568e+06
1.23E+06
1.23457e+06 0.000123 12.3
14.29%
2 4

Thousands separators

The , and _ options group digits by thousands. For binary, octal, and hexadecimal output, the underscore groups by four digits. Python 3.14 extended the grouping to the fractional part of a number.

grouping.py
val = 1_200_400_001
amount = 1234567.891234

print(val)
print(f'{val:_}')
print(f'{val:,}')
print(f'{amount:,.2f}')
print(f'{0xdeadbeef:_x}')
print(f'{0b1011001110001111:_b}')
print(f'{amount:,.6_f}')
print(f'{amount:_._f}')

The grouping option comes after the width and before the precision, as in ,.2f.

print(f'{amount:,.6_f}')
print(f'{amount:_._f}')

A grouping character after the precision groups the digits after the decimal point into threes. The integral and fractional parts can use different separators. Python 3.13 and older reject these specifiers with a ValueError.

$ python grouping.py
1200400001
1_200_400_001
1,200,400,001
1,234,567.89
dead_beef
1011_0011_1000_1111
1,234,567.891_234
1_234_567.891_234

Format width

A number after the colon sets the minimum width of the field. Numbers are right-aligned by default; a leading zero before the width pads them with zeros.

width.py
for x in range(1, 11):
    print(f'{x:02} {x*x:3} {x*x*x:4}')

The first column is zero-padded to two digits, the second is right-aligned in three characters, and the third in four.

$ python width.py
01   1    1
02   4    8
03   9   27
04  16   64
05  25  125
06  36  216
07  49  343
08  64  512
09  81  729
10 100 1000

Building a table

Width, alignment, and precision together produce aligned tabular output.

table.py
items = [
    ('coffee', 3, 4.5),
    ('croissant', 12, 1.95),
    ('orange juice', 1, 13.0),
]

print(f'{"Item":<14}{"Qty":>5}{"Price":>10}')
print(f'{"":-<29}')

for name, qty, price in items:
    print(f'{name:<14}{qty:>5}{price:>10.2f}')

total = sum(qty * price for _, qty, price in items)
print(f'{"Total":<14}{total:>15.2f}')

Item names are left-aligned in 14 characters, the quantities right-aligned in 5, and the prices right-aligned in 10 with two decimal places. The header uses the same widths so that the columns line up.

print(f'{"":-<29}')

An empty string padded with dashes to 29 characters draws the separator line.

$ python table.py
Item            Qty     Price
-----------------------------
coffee            3      4.50
croissant        12      1.95
orange juice      1     13.00
Total                   49.90

Alignment and fill characters

The <, ^, and > options align the value to the left, center, or right of the field. Any single character placed before the alignment option is used for the padding.

justify.py
words = ['sky', 'fork', 'small']

for word in words:
    print(f'|{word:>10}|{word:^10}|{word:<10}|')

title = 'TITLE'

print(f'{title:*^30}')
print(f'{title:->30}')
print(f'{title:.<30}')
print(f'{42:#>10}')
print(f'{-42:=8}')
print(f'{-42:0=8}')

Strings are left-aligned by default, numbers right-aligned. When centering leaves an odd number of fill characters, the extra one goes to the right.

print(f'{-42:=8}')
print(f'{-42:0=8}')

The = alignment, valid only for numbers, puts the padding between the sign and the digits.

$ python justify.py
|       sky|   sky    |sky       |
|      fork|   fork   |fork      |
|     small|  small   |small     |
************TITLE*************
-------------------------TITLE
TITLE.........................
########42
-     42
-0000042

Sign control

The sign option controls the sign of numbers: + shows it for both positive and negative numbers, - (the default) only for negative ones, and a space reserves a blank position for positive numbers.

signs.py
numbers = [42, -42, 0]

print(f'{numbers[0]:+d} {numbers[1]:+d} {numbers[2]:+d}')
print(f'{numbers[0]:-d} {numbers[1]:-d} {numbers[2]:-d}')
print(f'{numbers[0]: d} {numbers[1]: d} {numbers[2]: d}')

for n in numbers:
    print(f'[{n:+6d}]')

tiny = -0.0001
print(f'{tiny:.2f} {tiny:z.2f}')

The space option keeps positive and negative numbers aligned without printing a plus sign.

tiny = -0.0001
print(f'{tiny:.2f} {tiny:z.2f}')

A small negative number rounded to zero is shown as -0.00. The z option, added in Python 3.11, turns the negative zero into a plain 0.00.

$ python signs.py
+42 -42 +0
42 -42 0
 42 -42  0
[   +42]
[   -42]
[    +0]
-0.00 0.00

Numeric notations

Integers can be printed in hexadecimal, octal, binary, or scientific notation. The # option adds the 0x, 0o, or 0b prefix.

notations.py
val = 300

print(f'{val:x} {val:X} {val:o} {val:b}')
print(f'{val:#x} {val:#X} {val:#o} {val:#b}')
print(f'{val:#06x}')
print(f'{val:016b}')
print(f'{val:e}')
print(f'{65:c}{66:c}{67:c} {0x1F40D:c}')

The x, X, o, and b types select the base. With the # option and zero padding, #06x produces a six-character hexadecimal number including the prefix. The c type converts an integer to the corresponding Unicode character.

$ python notations.py
12c 12C 454 100101100
0x12c 0X12C 0o454 0b100101100
0x012c
0000000100101100
3.000000e+02
ABC 🐍

Formatting bytes

The bytes and bytearray types have no format specifiers of their own; in an f-string they are shown with their repr. To get readable text or hexadecimal digits, decode or convert them first.

bytes_fmt.py
data = b'Hello'
buf = bytearray([72, 101, 108, 108, 111])

print(f'{data}')
print(f'{data.decode()}')
print(f'{buf}')
print(f'{data.hex()}')
print(f'{data.hex(" ")}')
print(f'{" ".join(f"{b:08b}" for b in data[:2])}')
print(f'{len(buf)} bytes: {list(buf)}')

The decode method turns the bytes into a string. The hex method returns hexadecimal digits, optionally with a separator between the bytes.

print(f'{" ".join(f"{b:08b}" for b in data[:2])}')

Iterating over a bytes object yields integers, so each byte can be formatted as an eight-digit binary number with 08b.

$ python bytes_fmt.py
b'Hello'
Hello
bytearray(b'Hello')
48656c6c6f
48 65 6c 6c 6f
01001000 01100101
5 bytes: [72, 101, 108, 108, 111]

Formatting enums

How an enum member appears in an f-string depends on the enum type. A plain Enum shows the class and member name, while IntEnum and StrEnum members behave like their values.

enums.py
from enum import Enum, IntEnum, StrEnum


class Status(Enum):
    SUCCESS = 1
    FAILURE = 2


class Priority(IntEnum):
    LOW = 1
    HIGH = 2


class Color(StrEnum):
    RED = 'red'
    GREEN = 'green'


print(f'{Status.SUCCESS} {Status.SUCCESS!r}')
print(f'{Status.SUCCESS.name} {Status.SUCCESS.value}')
print(f'{Priority.HIGH} {Priority.HIGH:03d}')
print(f'{Color.RED} {Color.RED:>8}|')

The name and value attributes give the member name and its value. IntEnum and StrEnum members accept the format specifiers of int and str. Since Python 3.11, which also added StrEnum, both str and format give their plain value rather than the member name.

$ python enums.py
Status.SUCCESS <Status.SUCCESS: 1>
SUCCESS 1
2 002
red      red|

Complex numbers

Complex numbers accept the float presentation types; the precision applies to both the real and the imaginary part.

complex_nums.py
c = 3.14159 + 2.71828j

print(f'{c}')
print(f'{c:.2f}')
print(f'{c:>20.3f}|')
print(f'{c.real:.3f} and {c.imag:.3f}j')
print(f'{abs(c):.4f}')

Without a specifier the number is shown in parentheses. With a specifier such as .2f the parentheses are omitted. The real and imag attributes and the abs function can be formatted separately.

$ python complex_nums.py
(3.14159+2.71828j)
3.14+2.72j
        3.142+2.718j|
3.142 and 2.718j
4.1544

Nested f-strings

An f-string can contain another f-string in one of its expressions. This is useful for formatting the items of a collection before joining them.

nested_fstrings.py
price = 49.99
items = {'pen': 1.5, 'notebook': 4.25}

print(f'Price: {f"${price:.2f}" if price > 0 else "free"}')
print(f'Items: {", ".join(f"{k}={v:.2f}" for k, v in items.items())}')

The inner f-string f"${price:.2f}" is evaluated only when the condition is true. In the second line, a generator expression builds an f-string for each dictionary item, and join combines them. Before Python 3.12, nested f-strings had to use a different quote type at each level, which limited the nesting to four levels; this limit is gone now.

$ python nested_fstrings.py
Price: $49.99
Items: pen=1.50, notebook=4.25

Syntax rules

A few constructs need care inside replacement fields: the colon starts a format specifier and ! a conversion, so expressions that contain them at the top level must be wrapped in parentheses.

syntax_rules.py
nums = [4, 8, 15, 16, 23, 42]

print(f'{(n := len(nums))} numbers, average {sum(nums) / n:.2f}')
print(f'{(lambda x: x * 2)(21)}')
print(f'{nums[1:3]} {nums[::-2]}')
print(f'{ {"a": 1}["a"] }')
print(f'{
    sum(nums)  # all the numbers
}')

try:
    eval("f'{lambda x: x * 2}'")
except SyntaxError as e:
    print(f'SyntaxError: {e.msg}')

The assignment expression := and the lambda both contain a colon, so they must be enclosed in parentheses. Colons inside brackets, such as slices, are fine.

print(f'{ {"a": 1}["a"] }')

A dictionary literal directly after the opening brace would read as {{, an escaped brace; a space separates the two.

print(f'{
    sum(nums)  # all the numbers
}')

Since Python 3.12, replacement fields can span multiple lines and contain comments, even in single-quoted f-strings.

$ python syntax_rules.py
6 numbers, average 18.00
42
[8, 15] [42, 16, 8]
1
108
SyntaxError: f-string: lambda expressions are not allowed without parentheses

When not to use f-strings

An f-string is evaluated immediately, where it appears. This is not always desirable. Logging calls should pass the values as arguments so that the message is built only when the record is actually emitted.

lazy_logging.py
import sys
import logging

logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s',
                    stream=sys.stdout)


class Expensive:
    def __str__(self):
        print('  str() called')
        return 'expensive object'


obj = Expensive()

print('f-string:')
logging.debug(f'Value: {obj}')

print('lazy %-style arguments:')
logging.debug('Value: %s', obj)

print('INFO level:')
logging.info('Value: %s', obj)

The Expensive class reports when its __str__ method runs. The f-string converts the object even though the DEBUG message is discarded. With %-style arguments, the logging module formats the message only when the level is enabled.

For the same reason, f-strings must never be used to build SQL queries, shell commands, or HTML from untrusted input; use query parameters or proper escaping. Python 3.14 added template strings (t-strings), which keep the static parts and the interpolated values apart so that they can be processed safely.

$ python lazy_logging.py
f-string:
  str() called
lazy %-style arguments:
INFO level:
  str() called
INFO Value: expensive object

Source

f-strings – Python language reference

Format Specification Mini-Language

PEP 701 – Syntactic formalization of f-strings

In this article we have formatted strings in Python with f-strings. See also Python template strings and datetime formatting with f-strings.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.