Q&A library Python

How do I format numbers and text with f-strings in Python?

Python Beginner formattingf-stringsstrings

Short answer

Put an f before the quote and drop expressions in braces. A colon after the expression adds a format spec, such as .2f for two decimals or a comma for thousands separators.

The short version

Prefix the string with f and put expressions inside braces. To control how a value is displayed, add a colon and a format spec after the expression, for example {value:.2f} for two decimal places or {count:,} for thousands separators. F-strings are the clearest and fastest formatting option in modern Python.

The basics

name = "Ana"
score = 92
print(f"{name} scored {score}")   # Ana scored 92

Anything inside braces is evaluated, so you can put whole expressions there, not just variable names.

print(f"Double is {score * 2}")   # Double is 184

Formatting numbers

The part after the colon is a format specification. A few common ones:

value = 3.14159
print(f"{value:.2f}")     # 3.14, two decimal places
print(f"{value:.0f}")     # 3, rounded to whole

n = 1000000
print(f"{n:,}")           # 1,000,000, grouped thousands

ratio = 0.25
print(f"{ratio:.1%}")     # 25.0%, as a percentage

Aligning and padding

You can set a width and alignment, which is handy for lining up columns of text.

print(f"{'pen':<10}|")    # left aligned in 10 chars
print(f"{'pen':>10}|")    # right aligned
print(f"{42:05d}")        # 00042, zero padded to 5 digits

The debugging shortcut

An = inside the braces prints both the expression and its value, which is excellent for quick debugging.

print(f"{score=}")        # score=92

Why f-strings over the older ways

Older code uses "%s" % value or "{}".format(value). F-strings do the same job but keep the value next to where it appears in the text, so there is no counting of positional arguments and no jumping between the template and a separate argument list. They are also faster. For any new code, prefer f-strings.

The one thing to watch

To include a literal brace, double it: f"{{literal}}" prints {literal}. And remember the leading f; without it the braces are just characters and nothing is substituted, which is an easy mistake to miss.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project