Python String Formatting
Python · Tooling & Errors
Theory
String formatting builds text from values. The modern way is the f-string: put f before the quotes and write any expression inside braces, f'{name} earns {salary}'. Python evaluates each expression and inserts the result. After a colon you can add a format specifier that controls how the value looks.
Useful specifiers: :, adds thousands separators (65000 -> 65,000), :.2f rounds to two decimals (3.14159 -> 3.14), :.1% shows a fraction as a percentage (0.256 -> 25.6%), :>8 right-aligns in 8 characters and :03d pads an integer with zeros (7 -> 007). Older styles still appear in existing code: str.format() ('{} earns {}'.format(name, salary)) and % formatting ('%s earns %d' % (name, salary)).
Why we use it
Reports, logs and messages need numbers shown cleanly - currency with separators, rounded ratios, aligned columns. f-strings do this inline and readably without manual str() conversion and concatenation.
When to use it
Use f-strings for nearly all formatting in Python 3 code. Use str.format() when the template is stored separately from the values, and never build SQL queries with f-strings - use parameterised queries.
How it works
- Write f'{name} earns {salary:,}'
- Find each {...} placeholder
- Evaluate the expression inside the braces
- Is there a format spec after ':'? Yes: Apply it, e.g. add commas. No: Use the default str() form.
- Final string: Asha earns 65,000
Syntax
f'{expression}'Example
name = 'Asha'
salary = 65000
print(f'{name} earns {salary:,}')Key points
- f-strings are the modern, readable formatting standard
- Supports format specifiers like :.2f and :,
- Any expression works inside braces, e.g. {salary * 12}
- f'{x=}' prints both the expression and its value, handy for debugging
- Never use f-strings to build SQL from user input