Strings
String Formatting
f-strings, format(), % formatting
Interview: Modern Python practices
Last Updated: June 12, 2026
•
7 min read
Python offers several ways to format strings, but f-strings (Python 3.6+) are the modern standard. They're faster, more readable, and support inline expressions and format specifications.
F-Strings (Python 3.6+)
- Prefix with
forFbefore the string - Embed expressions in
{curly braces} - Support format specifiers:
{value:.2f},{name:>10} - Can call functions, access dict keys, and use expressions:
{len(items)} - Python 3.8+ supports
{expr=}for debugging:f"{x=}"outputs "x=5" - Python 3.12+ allows f-string nesting and backslashes inside braces
Format Specification Mini-Language
{v:.2f}— 2 decimal places (3.14){v:.2e}— scientific notation (3.14e+00){v:,}— thousands separator (1,234,567){v:.1%}— percentage (75.0%){v:>10}/{v:<10}/{v:^10}— alignment{v:08b}— binary, zero-padded (00001010){v:#x}— hex with prefix (0xff)
Legacy Formatting
str.format():"{0} is {1}".format(name, age)— still used in older codebases%operator:"%s is %d" % (name, age)— C-style, avoid in new codeTemplate strings:Template("$name is $age").substitute(name=name, age=age)— safe for user input
Use Cases
Building user-facing messages and reports
Formatting numerical data for display (currency, percentages)
Debug logging with f-string debug syntax (Python 3.8+)
Safe template rendering with untrusted user input
Common Mistakes
Using % formatting or .format() when f-strings are available
Forgetting that f-strings are evaluated at creation time (not lazy)
Not using format specifiers for alignment in tabular output
Using f-strings with untrusted input (use Template instead)