Skip to content

string formatting

In Python, string formatting is the process of building a string from a template that holds placeholders for values to be filled in. Each placeholder can carry a format specification that controls how its value is rendered, including field width, alignment, and the number of decimal places.

Modern code does this with f-strings, which embed expressions directly inside a string literal prefixed with f. Two older approaches are still valid and widely used. The .format() method fills numbered or named placeholders from its arguments, and printf-style formatting, named after C’s printf() function, interpolates a tuple or dictionary through the % operator.

Both f-strings and .format() share a format specification mini-language, written after a colon inside the placeholder. A spec such as >8.2f right-aligns a number in a field eight characters wide and rounds it to two decimal places. Because the placeholder converts each value to its string form on the way in, formatting a number into a message needs no explicit str() call.

Change the alignment, width, and precision below to watch each part of the spec reshape the field that the value lands in:

Interactive diagram — enable JavaScript to view.

Example

Say you’re printing a receipt line and need the product name padded to a fixed width so the prices line up in a column. All three formatting styles produce the same result:

Language: Python
>>> product = "Widget"
>>> price = 12.5

>>> f"{product:<10}{price:>8.2f}"
'Widget       12.50'

>>> "{:<10}{:>8.2f}".format(product, price)
'Widget       12.50'

>>> "%-10s%8.2f" % (product, price)
'Widget       12.50'

Each version left-aligns product in a ten-character field, then right-aligns price in an eight-character field with two decimal places. The f-string reads the names straight from the surrounding scope, .format() takes them as arguments, and the % operator takes them as a tuple.

Python String Formatting: Available Tools and Their Features

Tutorial

Python String Formatting: Available Tools and Their Features

In this tutorial, you'll learn about the main tools for string formatting in Python, as well as their strengths and weaknesses. These tools include f-strings, the .format() method, and the modulo operator.

basics best-practices python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Martin Breuss • Updated Sept. 16, 2026