PythonPython StringsPython string formatting

What are f-strings in Python?

Question 66 of 88 · Updated

On this page

An f-string (formatted string literal) is a Python string literal prefixed with f or F that evaluates expressions inside curly braces and inserts their formatted values into the resulting str. Introduced in Python 3.6 by PEP 498, f-strings make it easy to combine computed values and surrounding text without manually converting and concatenating every fragment.

1. Basic syntax and expression interpolation#

PYTHON
name = 'Ada' items = 3 print(f'{name} has {items} items.') print(f'{items * 2} after doubling')

Output:

Ada has 3 items.
6 after doubling

The expressions inside braces are called replacement fields. They may contain variables, arithmetic expressions, attribute access, indexing and function calls. The prefix is essential: without it, ordinary braces in a string literal remain ordinary text.

Unlike a template retained for later evaluation, an f-string evaluates its expressions when execution reaches the literal. The result is an ordinary immutable string.

2. How replacement fields are evaluated#

A useful simplified field syntax is:

{expression[=][!conversion][:format_spec]}

The square brackets in this notation indicate optional components; they are not literal syntax. The equals sign is the optional debugging form discussed below.

Loading diagram…

This is the conceptual formatting path for an ordinary replacement field. Dynamic specifications can themselves contain expressions, and evaluation or formatting can raise exceptions.

Replacement-field expressions are evaluated from left to right. Repeated expressions are not automatically cached.

PYTHON
events = [] def record(x): events.append(x) return x print(f'{record(1)}:{record(2)}:{record(1)}') print(events)

Output:

1:2:1
[1, 2, 1]

The calls occur three times, including the repeated call with argument 1. Keep interpolation expressions simple and avoid hiding expensive operations or consequential side effects inside a display string.

3. Conversion flags and literal braces#

FlagMeaning
!sApply str() before formatting
!rApply repr() before formatting
!aApply ascii() before formatting
No flagUse the value's formatting protocol directly
PYTHON
text = 'café\n' print(f'{text!r}') print(f'{text!a}') print(f'{{status}} = {42}')

Output:

'café\n'
'caf\xe9\n'
{status} = 42

The representation conversion exposes the newline as escaped notation. The ASCII conversion additionally escapes the non-ASCII character. These representations are useful for diagnostics but are not general-purpose serialization or security escaping.

To insert literal braces in the literal-text portion of an f-string, double them: {{ and }}. Braces inside a replacement-field expression instead follow Python expression syntax.

4. Format specifiers#

A colon introduces a format specification. It controls how the resulting value is represented, according to the type's formatting protocol.

PYTHON
print(f'{12:05d}') print(f'{12345:,d}') print(f'{0.125:.1%}') print(f'|{"id":>6}|')

Output:

00012
12,345
12.5%
|    id|
SpecificationTypical use
.2fFixed-point representation with two decimal places
05dDecimal integer with minimum width five, zero-padded
,dInteger with comma grouping
.1%Percentage with one decimal place
>6Right alignment in a field of minimum width six
<6Left alignment in a field of minimum width six
^6Center alignment in a field of minimum width six
xLowercase hexadecimal integer

The format specification mini-language is shared with format() and str.format() for types that implement it. Not every specification works for every type. In particular, width is generally a minimum rather than a maximum; it does not automatically truncate oversized values.

Formatting a floating-point number to two decimal places changes its displayed representation, not the stored value or the accuracy of previous arithmetic. Width calculations also do not guarantee correct visual alignment for arbitrary Unicode terminal text.

5. Dynamic format specifications and debugging#

PYTHON
width = 8 precision = 2 value = 12.375 print(f'|{value:{width}.{precision}f}|') print(f'{value=:.2f}')

Output:

|   12.38|
value=12.38

Nested replacement fields construct the specification 8.2f. This allows width and precision to be supplied by program state. If these settings originate from external input, validate them: very large widths or precision can create excessive output.

The debugging equals form was introduced in Python 3.8. A field such as f'{value=}' includes the expression text, an equals sign and its representation. It uses repr by default when no explicit conversion or format specification is supplied. Adding a specification, as in this example, uses that formatting unless a conversion is explicitly requested.

Do not use debugging fields to log credentials or sensitive personal data.

6. The object formatting protocol#

F-strings are not simply a shorthand for applying str() to everything. When no explicit conversion is requested, Python uses the object's __format__ protocol, conceptually equivalent to format(value, spec).

PYTHON
class Ticket: def __format__(self, spec): if spec == 'short': return 'T-007' if spec == '': return 'Ticket 007' raise ValueError('unsupported format') ticket = Ticket() print(f'{ticket}', f'{ticket:short}')

Output:

Ticket 007 T-007

The class defines its own supported specifications, including the empty specification. A custom __format__ must return a string. The standard mini-language is a convention implemented by many built-in types, not a universal requirement for every class.

An explicit conversion such as !r is applied before the resulting string is formatted. The original object's custom formatting behavior is therefore not necessarily used when a conversion is present.

7. Practical example: format a monetary total#

PYTHON
from decimal import Decimal price = Decimal('12.50') quantity = 3 print(f'Total: {price * quantity:.2f}')

Output:

Total: 37.50

Decimal constructed from decimal text is suitable for decimal arithmetic in this example. The f-string formats the computed total with two decimal places.

In financial software, explicitly define the currency, rounding policy, calculation precision and locale-specific presentation. An f-string is a presentation mechanism, not a monetary calculation or validation framework.

8. Python version compatibility#

VersionRelevant feature
3.6F-strings introduced by PEP 498
3.8Debugging equals syntax
3.12PEP 701 formalized the grammar and removed several previous expression restrictions

Python 3.12 and later support reusing the outer quotation style inside replacement expressions and allow backslashes in valid embedded expressions. They also allow comments in replacement fields under the applicable grammar rules; a closing brace cannot appear inside a comment.

PYTHON
data = {'name': 'Ada'} print(f"{data["name"]}") print(f"{'\n'.join(['a', 'b'])}")

Output on Python 3.12+:

Ada
a
b

Both examples were executed on CPython 3.13.5. They do not parse on Python 3.11. For older deployment targets, choose a different inner delimiter for the first example and calculate the joined text before interpolation in the second.

PEP 701 does not remove ordinary expression rules or make arbitrary statements valid replacement fields. For instance, an assignment expression used in a replacement field requires suitable parentheses.

9. Raw f-strings and evaluation timing#

PYTHON
name = 'Ada' print(rf'C:\users\{name}') text = f'Hello {name}' name = 'Lin' print(text, f'Hello {name}')

Output:

C:\users\Ada
Hello Ada Hello Lin

The rf prefix combines raw literal-text handling with expression interpolation. Backslashes in the literal-text portion are preserved subject to raw-string lexical rules. Replacement-field expressions still follow normal Python expression rules.

The variable text holds the already constructed string. Changing name does not retroactively change text; evaluating a new f-string uses the new value.

A raw prefix does not disable interpolation, and f-strings cannot be combined with the bytes-literal prefix to create formatted bytes literals. Encode the final text separately when a binary representation is required.

10. Failure modes and security#

ExpressionFailure
f'{}'SyntaxError: empty field
f'{1'SyntaxError: unclosed field
f'{1!q}'SyntaxError: unsupported conversion
f'{123:.2fQ}'ValueError: invalid numeric format
f'{missing}'NameError if missing is undefined
f'{1/0}'ZeroDivisionError during expression evaluation

A syntax failure prevents the affected source from compiling; evaluation and formatting failures occur at runtime.

Interpolated user data is not recursively evaluated as Python source. However, f-strings do not provide SQL parameterization, HTML escaping or shell argument safety. Use the interface appropriate to the destination. Never use eval to execute a user-supplied f-string template.

For logging, consider the logging module's deferred argument formatting when a message may be disabled. An f-string is evaluated eagerly before the logging call, even if the message is not emitted.

11. Complexity and choosing f-strings#

The work includes evaluating field expressions, converting and formatting their results, and assembling output. Under a bounded-cost model for field evaluation and formatting, assembling L output code points requires work proportional to the text produced, except for trivial cases and implementation optimizations. Arbitrary custom formatting or expensive field expressions can dominate the cost.

F-strings are particularly readable for fixed, source-defined messages. Use join for arbitrary collections of text fragments and a dedicated serializer for structured output. The next lesson compares f-strings with str.format() and percent formatting, including situations where a runtime template is needed.

Interview-ready answer#

F-strings are formatted string literals introduced in Python 3.6. Prefix a literal with f and place expressions inside braces; Python evaluates those expressions at runtime and produces a str. Replacement fields support conversions such as !r, format specifications such as .2f, dynamic specifications and the debugging equals syntax. The value's __format__ protocol controls formatting unless an explicit conversion changes the value being formatted. Double braces produce literal braces. Python 3.12 expanded the permitted replacement-field syntax through PEP 701. F-strings are eager and convenient for source-defined messages, but they are not serializers or security-escaping mechanisms.

Official references#

Verification note: All nine runnable examples matched their expected outputs in independent namespaces on CPython 3.13.5. Six independent expected-exception tests passed. Python 3.11 was not separately executed. The fenced Mermaid diagram was manually reviewed; the local Mermaid package and CLI were unavailable, so parser validation and public-site rendering were not performed. Official references are supplied under the authorized offline research exception; live documentation and Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design