2 minutes
f-Strings: Fast and Friendly Formatting
Welcome to part five of our Python 3 features series! Today we’re looking at f-strings, cool numeric literal tricks, and a bit of extra syntax sugar that makes Python code a joy to write.
Before f-strings (Python 3.6+), we had %
formatting and str.format()
, which can feel clunky:
name = 'Alice'
age = 30
# Old ways:
print('Hello, %s! You are %d.' % (name, age))
print('Hello, {}! You are {}.'.format(name, age))
With f-strings, just put an f
before the quote and embed expressions directly:
print(f"Hello, {name}! You are {age}.") # Hello, Alice! You are 30.
Formatting Options
Inside {}
, you can use format specs just like str.format()
:
pi = 3.14159265
print(f"Pi rounded: {pi:.2f}") # Pi rounded: 3.14
print(f"Binary: {age:b}") # Binary: 11110
print(f"Padded: {age:0>4}") # Padded: 0030
Expression and Debugging Support (Python 3.8+)
You can even put more complex stuff in there:
print(f"Next year I'll be {age + 1}.") # Next year I'll be 31.
Plus, Python 3.8 added debugging support:
print(f"{name=}, {age=}") # name='Alice', age=30
That {var=}
shows both the name and value, super handy for quick prints.
Numeric Literal Underscores: Readable Numbers
Big numbers can be hard to parse at a glance. Python 3.6+ lets you sprinkle _
inside numeric literals:
# Integers:
one_million = 1_000_000
binary_mask = 0b_1111_0000
hex_color = 0xFF_FF_FF
# Floats:
ratio = 3.14_15_92
The underscores don’t affect the value, they just help you read big numbers quickly.
A Taste of Extra Sugar
Here’s a small one: trailing commas in tuples, lists, and function arguments are totally fine, and sometimes encouraged for cleaner diffs:
points = [
(0, 0),
(1, 2),
(2, 4), # note trailing comma!
]
def foo(
a,
b,
c, # trailing comma here too
):
pass
That way if you add a new line later, your diff only shows the new line.
That’s it for part five: f-strings, numeric literal underscores, and a pinch of extra sugar to keep your code neat. Next up, we’ll dig into dataclasses and context variables for super-simple data containers and async context management. Happy coding!