Skip to content
Elephant House Logo

Dynamic f-string Formatting with Variables

Python f-strings support dynamic format specifiers by wrapping variables in additional curly brackets. This lets you control formatting at runtime instead of hardcoding values.

Basic String Padding

Here’s a simple right-aligned string with dots:

>>> text = "Hello World"
>>> f"{text:.>20}"
'.........Hello World'

The .>20 means: fill with ., align right (>), width 20.

Making It Dynamic

What if the width needs to change? Wrap the variable in extra braces:

>>> text = "Hello World"
>>> width = 20
>>> f"{text:.>{width}}"
'.........Hello World'

This works for any part of the format spec:

>>> value = 3.14159
>>> precision = 2
>>> f"{value:.{precision}f}"
'3.14'

Not a Python 3.12 Feature

Despite the timing of Python 3.12’s f-string formalization (PEP 701), this nested variable syntax has worked since f-strings were introduced in Python 3.6. The formalization made f-strings easier to parse and enabled things like nested quotes, but dynamic format specs were always supported.

Conclusion: If you’re hardcoding format widths or precisions in f-strings, consider whether a variable would make your code more flexible.

See all thoughts