Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python String Formatting: f-strings and str.format()

Use f-strings and str.format() in Python to control alignment, padding, numbers, dates, and custom objects. Includes format specifier examples and common pitfalls.

~5 min readPython
#f-strings#str.format#format specifiers#string interpolation
Illustration of Python string formatting showing f-string interpolation and format specifiers

When you need to format strings in Python, you may be choosing among the % operator, the str.format() method, and f-strings. Each has different syntax, capabilities, and tradeoffs. This article explains how they work, when to use each, and how to control alignment, padding, and number formatting with format specifiers.

The Main String Formatting APIs in Python

Python has several formatting tools. The three you are most likely to encounter are %-formatting, inherited from C's printf style; str.format(), introduced in Python 2.6; and f-strings, added in Python 3.6. The oldest, %-formatting, uses %s, %d, %f placeholders and a tuple or dictionary of values. While still functional, it is verbose and less flexible than the alternatives.

str.format() uses curly braces {} as placeholders. It supports positional and keyword arguments, and it can access object attributes and dictionary keys directly inside the braces.

F-strings combine the placeholder syntax of str.format() with inline expressions. An f-string is a string literal prefixed with f or F; expressions inside {} are evaluated at runtime and inserted into the string. Because the expression is written directly in the literal, f-strings are more readable and often faster than the other two approaches.

f-Strings: The Default Choice for Most Code

F-strings are the recommended way to format strings in modern Python. They are concise, support arbitrary expressions, and keep the format template close to the data being inserted.

python
name = "Ada" score = 92 message = f"{name} scored {score} points" print(message)

You can call methods, access list indices, or evaluate arithmetic inside the braces:

python
items = ["apple", "banana", "cherry"] print(f"First item: {items[0].upper()}") print(f"Sum: {sum([1, 2, 3])}")

F-strings also support format specifiers, which control alignment, width, precision, and number representation. The specifier follows the expression after a colon:

python
value = 12.34567 print(f"{value:.2f}") # 12.35

Because f-strings are evaluated at runtime, they work with any expression that can appear in Python code. They are the clearest choice for most formatting needs, especially when the format template is known at write time.

The str.format Method for Dynamic Formatting

str.format() remains useful when the format string is not known until runtime, for example when it comes from a configuration file or a user-provided template. The method accepts positional and keyword arguments:

python
template = "{name} has {count} items" print(template.format(name="Bob", count=3))

You can also use indexed placeholders to reuse arguments:

python
print("{0} and {1} and {0}".format("a", "b"))

str.format() supports the same format specifiers as f-strings. The main difference is that the values are passed separately, which makes it easier to build templates dynamically.

One limitation is that str.format() cannot access local variables implicitly; you must pass them explicitly. This can make the call site verbose when many values are involved. In such cases, f-strings are simpler.

Format Specifiers: Alignment, Padding, and Number Formatting

The format specifier mini-language controls how values are presented. It appears after the colon in both f-strings and str.format(). The general syntax is:

[[fill]align][sign][#][0][width][,][.precision][type]

Common uses include:

  • Alignment: < left, > right, ^ center. A fill character can precede the alignment symbol.
  • Width: minimum field width in characters.
  • Sign: + forces a plus sign for positive numbers, - is the default, and a space leaves a gap.
  • Zero padding: 0 before the width pads with zeros.
  • Number types: d for integers, f for fixed-point floats, e for scientific notation, % for percentage.
python
print(f"{42:>5}") # ' 42' print(f"{42:<5}") # '42 ' print(f"{42:^5}") # ' 42 ' print(f"{42:05}") # '00042' print(f"{3.14159:.2f}") # '3.14' print(f"{0.25:.0%}") # '25%'

For numeric types, you can also use comma or underscore as grouping separators:

python
print(f"{1234567:,}") # 1,234,567 print(f"{1234567:_}") # 1_234_567

These specifiers work identically in str.format(). Understanding them lets you produce consistent, well-aligned output for reports, logs, and user interfaces.

Formatting Dates, Times, and Custom Objects

Format specifiers are not limited to built-in types. You can define how your own objects are formatted by implementing the __format__ method. This method receives the specifier string and must return a string representation.

python
class Temperature: def __init__(self, celsius): self.celsius = celsius def __format__(self, spec): if spec == "f": return f"{self.celsius:.1f}°C" return f"{self.celsius}°C" temp = Temperature(21.5) print(f"{temp:f}") # 21.5°C

datetime objects also accept the same formatting directives that strftime uses, so timestamps can be formatted directly inside the format specifier:

python
from datetime import datetime now = datetime.now() print(f"{now:%Y-%m-%d %H:%M}")

This integration makes it easy to produce formatted timestamps without calling strftime separately.

Performance and Readability Tradeoffs

F-strings are generally faster than str.format() in CPython because the f-string template is parsed at compile time, while str.format() parses its template on each call. The expressions are still evaluated at runtime and converted to strings using the format() protocol.

For most applications the difference is negligible, but in tight loops that format thousands of strings, f-strings can reduce CPU usage. More importantly, f-strings improve readability because the values are inline, making it easier to see what will be inserted.

However, str.format() has a clear advantage when the template is dynamic. If you need to choose the format at runtime, perhaps from a data-driven configuration, str.format() is the only option among the two modern APIs. The % operator also supports dynamic templates, but it is less flexible.

Common Pitfalls and Compatibility Notes

F-strings require Python 3.6 or later. If you support older versions, you must use str.format() or %-formatting. Also, because f-strings evaluate expressions at runtime, they can have side effects if the expression calls a function that mutates state. Keep f-string expressions side-effect-free to avoid surprising behavior.

Escaping braces in f-strings and str.format() is a common source of errors. To include a literal { or }, double it:

python
print(f"{{literal}}") # {literal}

In str.format(), the same doubling applies. Nested format specifiers are possible in f-strings too, but if the whole specifier is built dynamically at runtime, str.format() may be clearer:

python
width = 10 value = 42 print(f"{value:>{width}}") # works in f-strings spec = ">10" print("{:{}}".format(value, spec))

Another pitfall is formatting a string that contains many literal braces, such as JSON or CSS. With both str.format() and f-strings, every literal brace must be escaped, which quickly becomes unreadable. In those cases, consider string.Template or a dedicated templating library.

Finally, be aware that %-formatting does not support the format specifier mini-language. It has its own conversion flags, which are more limited. For new code, prefer f-strings or str.format().

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.