PythonPython StringsPython string formatting

What is the difference between f-strings, `format()`, and `%` formatting?

Question 67 of 88 · Updated

On this page

Python provides three widely used ways to insert values into text: f-strings for source-defined expressions, str.format() for reusable brace-based templates, and the % operator for printf-style formatting. All three remain useful, but their syntax, evaluation model and formatting capabilities differ.

For new code targeting Python 3.6 or later, f-strings are usually the clearest choice for straightforward messages. Use str.format() when the template must be selected at runtime, and retain percent formatting where an existing interface expects it, notably standard-library logging calls with separate arguments.

1. The same result using all three approaches#

PYTHON
name = 'Ada' count = 7 print(f'{name}: {count:03d}') print('{name}: {count:03d}'.format(name=name, count=count)) print('%s: %03d' % (name, count))

Output:

Ada: 007
Ada: 007
Ada: 007

All three produce an ordinary str with the same contents. The integer is displayed with a minimum width of three and leading zeros. Its underlying numeric value remains seven.

FeatureF-stringstr.format()% formatting
Basic examplef'{x}''{}'.format(x)'%s' % x
Field syntaxPython expressionsPositional or named argument referencesConversion specifiers and optional mapping keys
Template supplied at runtimeNot directlyYesYes
Format languageType-specific __format__ protocolSame protocolPrintf-style conversions
Literal delimiter escapesDoubled bracesDoubled bracesDoubled percent signs
AvailabilityPython 3.6+Python 3 and older Python 2.6+Longstanding Python syntax
Typical choiceInline messagesReusable message templatesExisting printf-style interfaces and deferred logging

Here format() commonly refers to the str.format() method. Python also has a separate built-in format(value, spec), discussed in section 4.

2. The central difference: source expression versus runtime template#

An f-string is Python source syntax. Its replacement expressions are determined by the program's source and evaluated when execution reaches the literal. The preceding f-string lesson covers expression evaluation, conversion flags, PEP 701 and dynamic format specifications.

With str.format(), the format string is an ordinary runtime value. This makes it possible to select a trusted template separately from its data.

PYTHON
template = '{name} has {count} items' print(template.format(name='Ada', count=2)) print(template.format(name='Lin', count=5)) print('{1} / {0} / {1}'.format('A', 'B'))

Output:

Ada has 2 items
Lin has 5 items
B / A / B

The first two calls reuse a single template with different arguments. The final call references argument positions explicitly and uses the second argument twice.

Brace-based templates can use automatically numbered positional fields such as {}, explicitly numbered fields such as {0}, and named fields such as {name}. Automatic and explicit positional numbering cannot be mixed in a single format string.

Putting braces inside an ordinary string does not turn it into an f-string. Adding an f prefix to a reference to a variable cannot dynamically compile its contents into an f-string. Do not use eval to accomplish this.

3. Field access in str.format() and format_map()#

PYTHON
record = {'name': 'Ada', 'scores': [80, 95]} print('{r[name]}: {r[scores][1]}'.format(r=record)) print('{name}: {count}'.format_map({'name': 'Lin', 'count': 4}))

Output:

Ada: 95
Lin: 4

Unlike f-string expressions, str.format() fields do not evaluate arbitrary Python expressions. They support a restricted field-name grammar: an argument name or position can be followed by attribute access or item access.

In {r[name]}, name is interpreted as a string key by the formatting grammar, not as a Python variable expression. In an f-string, dictionary lookup instead uses normal Python syntax, such as r['name'].

The format_map method receives a mapping directly rather than unpacking it as keyword arguments. This can be useful with mapping subclasses that implement custom missing-key behavior. It is primarily for named fields, not positional arguments.

Restricted field syntax does not make an arbitrary template safe. Attribute and item access can expose data from supplied objects or invoke object behavior. Use trusted templates and a narrow set of appropriate values. For untrusted template authors, consider a deliberately constrained template mechanism rather than providing access to complex application objects.

4. Built-in format() versus str.format()#

PYTHON
value = 12.375 spec = '.2f' print(format(value, spec)) print('{:{}}'.format(value, spec)) print(f'{value:{spec}}')

Output:

12.38
12.38
12.38

The built-in format(value, spec) formats one object according to its type's formatting protocol. Its second argument is a format specification, not a complete message containing replacement fields.

The str.format() method formats a template with zero or more replacement fields. Nested fields can supply a dynamic specification, as shown in the second line. F-strings also support dynamic specifications.

This distinction is particularly useful when writing a reusable function that receives a value and a specification but does not need surrounding message text: format(value, spec) is the direct operation.

For compatible types, f-strings and str.format() use the same formatting machinery. Width, alignment, grouping and precision were introduced in the preceding lesson; they do not require a different mechanism simply because the template syntax changes.

5. Percent formatting and the tuple trap#

PYTHON
pair = (1, 2) print('pair=%s' % (pair,)) print('%(name)s: %(count)03d' % {'name': 'Ada', 'count': 7}) print('progress: %d%%' % 75)

Output:

pair=(1, 2)
Ada: 007
progress: 75%

The % operator interprets conversion specifiers in the format string. A tuple on the right generally supplies multiple positional arguments. A mapping supports named conversion fields such as %(name)s.

When a tuple itself should be formatted as one value, wrap it in a one-element tuple, as in (pair,). Writing 'pair=%s' % pair instead supplies two arguments for one field and raises TypeError.

Some frequently encountered conversions are:

ConversionTypical result
%sString representation
%rrepr representation
%aASCII representation
%dDecimal integer representation
%.2fFixed-point representation to two decimal places
%03dZero-padded decimal integer, minimum width three
%%Literal percent sign, consuming no value

Percent formatting is similar in appearance to C's printf formatting, but Python's accepted operand types and conversion behavior are governed by Python's own rules. For example, %d can truncate ordinary floating-point inputs toward zero, whereas the d format code in the brace-based mini-language requires an appropriate integer type. Neither formatting operation should be substituted for numeric validation.

Percent formatting also supports width and precision supplied through * in applicable positional formats. Its grammar is separate from the brace-based formatting mini-language; a conversion such as %s cannot be passed unchanged as the specification argument to format().

6. Custom objects: the formatting protocols are not identical#

PYTHON
class Label: def __str__(self): return 'plain' def __format__(self, spec): return 'custom:' + spec value = Label() print(f'{value:short}', '{:short}'.format(value)) print('%s' % value, f'{value!s}')

Output:

custom:short custom:short
plain plain

Both the f-string and str.format() call the custom __format__ protocol for the short specification. The percent-style %s conversion instead uses str(value). The explicit !s conversion in the f-string likewise converts the original object to a string before formatting.

This is why rewriting an old format expression can change behavior even when its intended output looks equivalent. Examine the actual conversion rules, type contracts and custom methods. Preserve explicit representation conversions where necessary.

7. Practical distinction: deferred logging#

PYTHON
import logging logger = logging.Logger('demo', level=logging.WARNING) class Value: def __str__(self): print('converted') return 'value' value = Value() logger.debug('item=%s', value) print('after deferred call') logger.debug(f'item={value}') print('after eager call')

Output:

after deferred call
converted
after eager call

Both debug messages are disabled by the logger's level. The first call passes a format string and a separate object, so its string conversion is not needed. The second constructs the f-string before the logger is called, causing the conversion to execute even though the message is disabled.

The relevant distinction is not that all percent formatting is lazy. An expression such as logger.debug('item=%s' % value) formats eagerly too. Deferral is provided by the logging API when the template and arguments are passed separately.

Argument expressions themselves are still evaluated before the logging call. Passing logger.debug('item=%s', expensive_function()) does not defer expensive_function(). Guard costly computations with an appropriate level check when needed.

Also distinguish logging's message argument convention from its Formatter style option, which controls the format of the surrounding log record. Changing Formatter's style to braces does not automatically change the interpolation convention for ordinary logger calls.

8. Choosing a formatting mechanism#

Loading diagram…

For a fixed message containing local variables and small expressions, f-strings minimize the distance between the value and its presentation. For a trusted configuration-driven or localized template, selecting the template separately can be more appropriate; a complete localization framework may also need pluralization, locale and translation support.

For a system that already expects percent-style templates, preserve that interface unless there is a reason to change it. Percent formatting is not universally deprecated merely because f-strings are newer.

None of these mechanisms automatically escapes text for SQL, HTML, JSON or shell commands. For structured or executable destinations, use the destination's serializer, parameterization or argument interface instead.

9. Failure modes and migration pitfalls#

ExpressionExpected exception
'{missing}'.format()KeyError
'{1}'.format('a')IndexError
'{} {0}'.format('a')ValueError
'%s' % (1, 2)TypeError
'%d' % 'abc'TypeError
format(42, 'Q')ValueError

Unlike malformed f-string syntax, a malformed runtime format template typically fails when the formatting operation executes, rather than when the Python source is compiled.

When migrating between formatting methods, check:

  • Whether conversion is through str, repr, ascii or the object's __format__ protocol.
  • Whether arguments are evaluated once or a repeated expression performs repeated work.
  • Whether tuple arguments are intended as one value or multiple arguments.
  • Whether format widths, precision, numeric conversion and literal delimiters preserve the exact output contract.
  • Whether the old interface defers formatting, especially for logging.

A migration is complete when behavior and relevant failure cases are preserved, not merely when the new source looks more modern.

10. Performance and engineering trade-offs#

F-strings often have lower overhead for simple source-defined formatting in CPython. However, no universal speed ranking is guaranteed. The result depends on runtime version, template complexity, argument types, custom conversion methods and the amount of output.

The total work includes obtaining arguments, processing fields, formatting values and constructing the result. Expensive expressions or custom formatting can dominate the assembly cost. Large dynamic width or precision values can also produce excessive output, so validate any externally supplied settings.

For performance-sensitive code, benchmark equivalent output and include the actual template and argument construction costs. For logging, benchmark enabled and disabled message levels separately. The tests for this lesson establish correctness, not a measured performance ranking.

Interview-ready answer#

F-strings evaluate source-defined Python expressions and format their results, making them a good default for inline messages. The str.format() method accepts a runtime template with positional or named fields and uses the same __format__ protocol as f-strings. The built-in format() formats a single value. Percent formatting uses its own printf-style conversions and remains useful for existing interfaces, especially logging APIs that accept a template and separate arguments for deferred formatting. Choose the approach based on template lifetime, formatting requirements, evaluation timing and compatibility. They are not automatically interchangeable for custom objects, numeric conversions or security-sensitive output.

Official references#

Verification note: Seven independent runnable Python example groups matched their documented outputs on CPython 3.13.5. Six expected-exception tests and 500 seeded randomized equivalence checks across the three formatting methods passed for ordinary strings and zero-padded integers. No cross-version or performance benchmark was executed. The fenced Mermaid flowchart was manually reviewed; the local Mermaid package and CLI were unavailable, so parser-level 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