Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python string formatting

Reference for Python string formatting: f-strings, the format specification mini-language, str.format() and old-style % formatting, with alignment, width and precision.

Python has three ways to build text from values: f-strings, the str.format() method and the older % operator. For new code, f-strings are the default choice: they are short, fast and the expressions sit right where the output appears. All three share the same core idea, which is a placeholder plus an optional format specification that says how to display the value.

This page is a map of all three. The format specification mini-language is the part worth learning well, because it is identical in f-strings, format() and str.format().

Python
name, score = "Ada", 93.456
print(f"{name} scored {score:.1f}")   # Ada scored 93.5

Try it

Python f-string basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python The format specification

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python format() and % formatting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Format specification

The text after the colon in {value:spec} follows this layout, where every part is optional:

TEXT
[[fill]align][sign][z][#][0][width][grouping][.precision][type]
Part Meaning
fill, align < left, > right, ^ centered, = pad after the sign. fill is any one character placed before the alignment.
sign + always shows a sign, - only for negatives (default), a space leaves room for a plus.
# Alternate form: 0x, 0b, 0o prefixes for integers.
0 Zero-pad numbers to the width, after the sign.
width Minimum field width.
, or _ Thousands separator (_ also groups binary, octal and hex in fours).
.precision Digits after the point for floats, maximum characters for strings.
type s string, d integer, b o x X bases, c character, f F fixed, e E scientific, g G general, % percent, n locale number.

Strings default to left alignment and numbers to right alignment. Dates and times accept strftime codes, and your own classes can define __format__() to accept any spec they like.

Conversion flags and nested fields

In f-strings and str.format(), !r applies repr(), !s applies str() and !a applies ascii() before formatting. A spec may itself contain replacement fields, as in {name:>{width}}. The = form, f"{x=}", prints the source text of the expression and its value, which is handy for debugging.

Choosing between them

  • f-strings (Python 3.6+): use them whenever the template is written in the source file. Since Python 3.12 they can reuse the same quote type inside the braces and span multiple lines in the expression.
  • str.format(): use it when the template comes from somewhere else, such as a config file or translation table, and is filled in later. See str.format() and str.format_map().
  • % formatting: still common in old code and the logging module. It takes a single value or a tuple, so "%s" % (1, 2) fails; wrap a lone tuple as "%s" % ((1, 2),).
  • Untrusted templates: never build an f-string from user input with eval(). For user-supplied templates prefer string.Template, which cannot run code.

Usage notes

  • Rounding. f"{2.675:.2f}" shows 2.67 because the float is not exactly 2.675. Use decimal.Decimal for money.
  • Wrong type code. f"{3.5:d}" raises ValueError; convert with int() first.
  • Missing keys and indexes. str.format() raises KeyError or IndexError; % raises TypeError for a wrong count of values.
  • Backslashes were not allowed inside f-string expressions before 3.12; they work now.
  • Logging should pass arguments lazily (log.info("x=%s", x)) instead of pre-formatting.