Coding Tricks

Python f-Strings: Tricks You Probably Haven’t Used

Most people learn one f-string trick, f"Hello {name}", and stop there. That’s a shame, because the part after the colon inside the braces is a small formatting language of its own, and Python 3.12 quietly removed most of the old annoying rules.

Below are the Python f-string tricks we think are worth knowing, from the debugging shortcut that saves you typing variable names twice to the 3.12 changes that let you reuse quotes and write comments inside the braces. We ran every snippet on Python 3.12.4, and the outputs shown are what it printed.

If you’re newer to Python, our 15 Python tricks for beginners is a gentler place to start. This one assumes you’ve written a few f-strings already.

The = specifier: f-string debugging in one character

Put = after an expression and Python prints the expression text, an equals sign and the value. It’s been around since Python 3.8, and plenty of developers still type print("score:", score) instead.

user = "ana"
score = 87.456

print(f"{user=}, {score=}")
# user='ana', score=87.456

print(f"{score = :.1f}")
# score = 87.5

print(f"{len(user) = }")
# len(user) = 3

Two details people miss. Spaces around the = are kept in the output, so {score = } prints score = 87.456. And it works on any expression, not just names, which is why len(user) = 3 shows up in full.

Notice that user came out with quotes. By default = shows the repr() of the value. Add a format spec, like :.1f, and Python switches to normal formatting instead.

!r, !s and !a: pick how the value is shown

These conversion flags run repr(), str() or ascii() on the value before formatting.

name = "Zoë"

print(f"{name!r}")    # 'Zoë'
print(f"{name!a}")    # 'Zo\xeb'
print(f"{name=!s}")   # name=Zoë
print(f"{name!r:>8}|")  #    'Zoë'|

Use !r in log lines and error messages. An empty string, a string with a trailing space and None all look different with quotes around them, and that’s usually the bug you’re hunting. !a is handy when output has to stay plain ASCII, such as some old terminals or log pipelines.

Python f-string formatting for numbers

This is where the format spec earns its keep. Thousands separators, percentages and scientific notation are all one or two characters.

price = 1234567.891

print(f"{price:,.2f}")     # 1,234,567.89
print(f"{price:_.0f}")     # 1_234_568
print(f"{0.4567:.1%}")     # 45.7%
print(f"{1234567:.2e}")    # 1.23e+06
print(f"{42:08.2f}")       # 00042.00
print(f"{-5:+} {5:+} {5: }")  # -5 +5  5

A few notes. The % type multiplies by 100 for you, so don’t do it yourself first. The underscore separator is useful when you’re printing numbers someone might paste back into Python code, since 1_234_568 is a valid integer literal. And the space sign option ({5: }) leaves room where a minus would go, so positive and negative numbers line up in a column.

Need a European style like 100.000? The format spec only offers comma and underscore. The quick workaround is f"{100000:,}".replace(",", "."). For real localisation, the locale module or a library like Babel is the right tool.

Binary, octal and hex

n = 255
print(f"{n:b} {n:o} {n:x} {n:X} {n:#x} {n:#010b}")
# 11111111 377 ff FF 0xff 0b11111111

The # adds the 0x or 0b prefix. In #010b, the width of 10 includes the prefix, which trips people up the first time.

Alignment and padding with f-strings

< aligns left, > aligns right and ^ centres. Put a character before them to use it as padding.

for item, qty in [("apples", 3), ("kiwi", 12), ("watermelon", 1)]:
    print(f"{item:<12}|{qty:>4}|")
# apples      |   3|
# kiwi        |  12|
# watermelon  |   1|

print(f"{'title':*^20}")   # *******title********
print(f"{5:=^9}")          # ====5====
Python f-string tricks cheat sheet for format specs

For quick terminal reports this is often all you need. Once a table has more than a handful of columns, or the data comes from a file, reach for a proper library instead of hand-tuning widths.

Nested format specs: widths that change at runtime

The format spec can contain its own braces. That lets you choose width, precision or even the alignment character from a variable.

width, prec = 10, 3
val = 3.14159265

print(f"{val:{width}.{prec}f}|")   #      3.142|

align = "^"
print(f"{'hi':{align}{width}}|")   #     hi    |

This is how you size a column to the longest item: compute width = max(len(s) for s in names) first, then drop it into the spec. Our guide to Python list comprehensions covers that kind of one-line calculation if it looks unfamiliar.

Formatting dates straight inside the braces

datetime objects accept strftime codes directly as the format spec, so you rarely need to call .strftime() yourself.

from datetime import datetime, date

now = datetime(2026, 11, 14, 18, 5, 9)
print(f"{now:%Y-%m-%d %H:%M}")      # 2026-11-14 18:05
print(f"{now:%A, %d %B %Y}")        # Saturday, 14 November 2026
print(f"{date(2026, 11, 14):%b %d}") # Nov 14
print(f"{now=:%Y-%m-%d}")           # now=2026-11-14

This works because datetime defines its own __format__ method. Month and day names like “Saturday” follow your system locale, so a server set to another language may print something else.

What changed for f-strings in Python 3.12

Python 3.12 shipped PEP 701, which made f-strings part of the real grammar instead of a special case. The What’s New in Python 3.12 page puts it simply: expression components “can now be any valid Python expression.” In practice that removed four restrictions that used to cause SyntaxErrors.

1. You can reuse the same quotes

songs = ["Hey Jude", "Yesterday"]
print(f"Top songs: {", ".join(songs)}")
# Top songs: Hey Jude, Yesterday

data = {"name": "Ana"}
print(f"Hello {data["name"]}")
# Hello Ana

According to the docs, Python 3.11 raised a SyntaxError here because the inner double quotes matched the outer ones. You had to switch to single quotes inside. On 3.12 both lines just run.

2. Backslashes are allowed in the expression

items = ["a", "b"]
print(f"Items:\n{"\n".join(items)}")
# Items:
# a
# b

print(f"{"\N{BLACK HEART SUIT}".join(["Eden", "Alkaline"])}")
# Eden♥Alkaline

Joining lines with "\n" inside the braces was probably the single most common f-string SyntaxError before 3.12. The old fix was a helper variable like nl = "\n". You can delete those now, as long as nobody runs your code on 3.11.

3. Multi-line expressions with comments

total = 3
print(f"Total: {
    total  # a comment inside the braces works in 3.12
}")
# Total: 3

Useful for long expressions, like a list you’d rather spread over several lines. Don’t overdo it. If the expression needs a comment to be understood, it probably wants to be its own variable with a good name.

4. Nesting as deep as you like, and clearer errors

print(f"{f"{f"{1+1}"}"}")
# 2

# A typo inside the braces:
my_string = f"{x z y}" + f"{1 + 1}"
#                ^^^
# SyntaxError: invalid syntax. Perhaps you forgot a comma?

Nobody needs three levels of nested f-strings. The error messages are the real win. When we ran that broken line on 3.12, the caret pointed straight at x z y. The 3.12 notes say 3.11 gave a vaguer “f-string: invalid syntax” with no precise location.

The catch with the 3.12 tricks: code that reuses quotes or puts a backslash inside the braces is a hard SyntaxError on Python 3.11 and older. Not a warning. The whole file refuses to load. If you publish a library, ship a script to a server you don’t control, or your team still has 3.11 somewhere, stick to the old style (different quotes inside, no backslashes) until you can set requires-python = ">=3.12".

More Python f-string tricks worth keeping

Literal braces, conditionals and calls

x = 10
print(f"{x if x > 5 else 'small'}")   # 10
print(f"{(lambda y: y * 2)(x)}")       # 20
print(f"{{literal braces}} and {x}")   # {literal braces} and 10

Double the braces to print them. A lambda has to be wrapped in brackets, because otherwise its colon would be read as the start of a format spec.

Your own classes can have format specs

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __format__(self, spec):
        if spec == "short":
            return f"({self.x},{self.y})"
        return f"Point(x={self.x}, y={self.y})"

p = Point(2, 3)
print(f"{p}  {p:short}")
# Point(x=2, y=3)  (2,3)

Whatever you write after the colon is handed to __format__ as a string. That’s the same hook datetime uses for its %Y codes, and it’s a neat way to give a class a short and a long display without extra methods.

Long messages without one giant line

msg = (
    f"User: {user}\n"
    f"Score: {score:.2f}\n"
)
print(msg, end="")
# User: ana
# Score: 87.46

Adjacent string literals inside brackets are joined automatically. Each line needs its own f prefix, though. Forget one and that line prints the braces as plain text, which is an easy bug to ship.

When not to use an f-string: logging

f-strings are evaluated the moment Python reaches them. Usually that’s what you want. In a logging call it isn’t, because the message gets built even when the log level means it’ll be thrown away.

import logging
logging.basicConfig(level=logging.WARNING)
log = logging.getLogger("demo")

class Expensive:
    def __str__(self):
        print("  (building the string...)")
        return "big report"

r = Expensive()
log.debug(f"Report: {r}")    # prints "(building the string...)"
log.debug("Report: %s", r)   # prints nothing

We ran this with the level set to WARNING. The f-string version still called __str__; the %-style version didn’t. The logging HOWTO explains that formatting of message arguments “is deferred until it cannot be avoided,” and that only works if you pass the values as arguments. For cheap values it hardly matters. In a hot loop or with expensive objects, use the %-style form.

The other case is templates that come from users or config files. An f-string is code, written in your source file, so it can’t be loaded from outside. That’s a good thing for safety. Use str.format() or string.Template for those, and never pass untrusted text to eval() to fake it.

Verdict

If you take one thing from this list, make it {value=}. It replaces most throwaway debug prints and costs one character. After that, learn :,.2f and the three alignment characters, and you’ll cover most real formatting jobs.

The 3.12 changes are pleasant rather than essential. Use them freely in your own projects. Skip them in anything that might still run on 3.11.

Picking up Python after JavaScript or another language? Our guide on how to learn programming with AI lists the habits that break quietly when you switch, like Python’s round(2.5) giving 2.

Next: f-strings pair well with comprehensions for quick reports. See 12 Python list comprehension patterns, all run on 3.12.

FAQ

Which Python version added the = specifier?

Python 3.8. It prints the expression text, an equals sign and the repr of the value, for example score=87.456.

Can I use the same quotes inside an f-string?

On Python 3.12 and newer, yes, thanks to PEP 701. On 3.11 and older it’s a SyntaxError, so use the other quote type inside the braces.

Are f-strings faster than str.format()?

In one quick timeit run on our Windows machine with Python 3.12.4, formatting a short string and an int took about 332 ns with an f-string and 628 ns with .format(). That’s one machine and one tiny case, so treat it as a hint. In real programs the difference rarely matters; pick f-strings for readability.

How do I print a curly brace in an f-string?

Double it. f"{{x}}" prints {x} as plain text.

Leave a Comment