W3docs

Format Strings

Learn all three ways to format strings in Python — % operator, str.format(), and f-strings — with examples covering numbers, alignment, and real-world use.

String formatting is how you embed variable values into text. Python offers three approaches: the legacy % operator, the versatile str.format() method, and the modern f-string syntax introduced in Python 3.6. Each produces the same result for simple cases, but they differ in power, readability, and the Python version they require.

This chapter covers:

  • The % operator and its type codes
  • str.format() with positional, index, and keyword placeholders
  • f-strings — inline expressions and the = debug specifier
  • Format specifiers: width, alignment, precision, and number bases
  • Choosing the right method for your situation

Related chapters: Python Strings · Concatenate Strings · Escape Characters · String Methods

The % Operator

The % operator is the oldest string formatting style in Python, borrowed from C's printf. You place type codes inside the string as placeholders, then supply the values after the % sign.

Common type codes

CodeMeaningExample inputOutput
%sString (or any object)"Alice"Alice
%dInteger4242
%fFloat3.143.140000
%rrepr() of the object"hi\n"'hi\n'

Format strings with %s and %d

python— editable, runs on the server
My name is John and I am 30 years old.

When you have more than one value, pass them in a tuple. The values are matched to placeholders left-to-right:

item = "coffee"
price = 2.50
qty = 3
print("Item: %s | Price: $%.2f | Qty: %d" % (item, price, qty))
Item: coffee | Price: $2.50 | Qty: 3

The %.2f format code rounds the float to 2 decimal places.

When to use %: Mainly when working with very old code or Python 2 codebases. For new code, prefer str.format() or f-strings.

str.format()

The str.format() method uses curly-brace placeholders {} and is more flexible than %. It supports positional arguments, index-based reuse, and named keyword arguments.

Positional Placeholders

Empty {} braces are filled left-to-right with the arguments you pass to format():

Format strings by format method in Python

python— editable, runs on the server
My name is John and I am 30 years old.

Index-Based Placeholders

Put a number inside the braces to pick a specific argument. You can also repeat the same argument:

name = "John"
age = 30
print("{0} is {1} years old and {0} likes Python.".format(name, age))
John is 30 years old and John likes Python.

Keyword Placeholders

Use keyword names for the most readable formatting. This also lets you reorder the values independently of the argument list:

name = "John"
age = 30
print("{name} is {age} years old.".format(name=name, age=age))
John is 30 years old.

You can unpack a dictionary directly with **:

person = {"name": "Alice", "city": "London"}
print("{name} lives in {city}.".format(**person))
Alice lives in London.

f-Strings (Python 3.6+)

f-strings (formatted string literals) are written by prefixing the string with f or F. Any expression inside {} is evaluated at runtime and converted to a string. They are the fastest and most readable option for modern Python code.

Format strings using f-strings in Python

python— editable, runs on the server
My name is John and I am 30 years old.

Because the braces can hold any valid Python expression, you are not limited to simple variable names:

x = 10
y = 3
print(f"{x} divided by {y} is {x / y:.2f}")
10 divided by 3 is 3.33

The = Debug Specifier (Python 3.8+)

Add = after the variable name to print both the variable name and its value — very useful for quick debugging:

val = 42
result = val * 2
print(f"{val=}, {result=}")
val=42, result=84

Format Specifiers

All three methods support a mini-language for controlling how values are displayed. The syntax inside {} for format() and f-strings is:

{[value]:[fill][align][sign][width][grouping][.precision][type]}

Alignment and Width

Use < (left), > (right), or ^ (center) with a width number:

name = "John"
print(f"|{name:<10}|")   # left-align in a field of width 10
print(f"|{name:>10}|")   # right-align
print(f"|{name:^10}|")   # center
|John      |
|      John|
|   John   |

You can specify a fill character before the alignment symbol:

print(f"|{'hello':*^15}|")  # fill with * and center
|*****hello*****|

Decimal Precision

pi = 3.14159265
print(f"Pi is approximately {pi:.2f}")   # 2 decimal places
print(f"Pi is approximately {pi:.4f}")   # 4 decimal places
Pi is approximately 3.14
Pi is approximately 3.1416

Number Formatting

price = 1234567.89
print(f"{price:,.2f}")   # comma as thousands separator
print(f"{price:e}")      # scientific notation
1,234,567.89
1.234568e+06

To display a ratio as a percentage, use the % type specifier:

ratio = 0.853
print(f"{ratio:.1%}")
85.3%

Integer Bases

x = 255
print(f"{x:d}")    # decimal   -> 255
print(f"{x:x}")    # hex lower -> ff
print(f"{x:X}")    # hex upper -> FF
print(f"{x:o}")    # octal     -> 377
print(f"{x:b}")    # binary    -> 11111111
255
ff
FF
377
11111111

The same specifiers work with str.format():

print("{:b}".format(255))   # 11111111
print("{:x}".format(255))   # ff

Zero-Padding

Pad an integer to a fixed width with leading zeros using 0 before the width:

print(f"{42:010d}")   # zero-pad to 10 digits
0000000042

Choosing the Right Method

SituationBest choice
Python 3.6 or newerf-string
Must support Python 2% operator
Reusing the same template stringstr.format() with a variable
Building templates at runtimestr.format()
Quick debug printf-string with = specifier
Old codebase to maintainMatch whatever style is already used

f-strings are the recommended default for all new Python 3 code. They are faster than str.format() (no method call overhead) and more readable than %.

Practice

Practice
Which of the following are correct ways to format strings in Python according to the content on the provided URL?
Which of the following are correct ways to format strings in Python according to the content on the provided URL?
Was this page helpful?