String Formatting
Python · Strings
Theory
An f-string is a string literal with an f prefix in which anything inside curly braces is evaluated as Python code and inserted as text. f'{name} earns {salary:,}' becomes 'Asha earns 65,000'. The expression can be a variable, arithmetic or even a method call like {name.upper()}, and it is evaluated at the moment the line runs, so the string always reflects current values.
After the expression you can add a colon and a format specifier to control how the value looks: :, adds thousands separators, :.2f rounds to 2 decimal places, :.1% shows a fraction as a percentage, and :>4 right-aligns in a field 4 characters wide. {salary=} prints both the expression and its value, which is handy when debugging. To show a literal brace, double it: {{ or }}. Older styles, .format() and % formatting, still work and appear in older code.
Why we use it
Reports, logs and messages mix fixed text with changing values. f-strings make that readable and handle number formatting (commas, decimals, percentages) without manual str() conversions or 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 (for example in a config file). Never build SQL queries with f-strings from user input; use parameters.
How it works
- Python meets f'{name} earns {salary:,}'
- Split the literal into fixed text and {...} fields
- Evaluate each field's expression: name -> 'Asha', salary -> 65000
- Does the field have a :format spec? Yes: Format the value with it, e.g. 65,000. No: Convert the value with str().
- Join all the pieces into one new string
- Output: 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 :.1%
- Any expression works inside the braces: {price * qty}
- {x=} prints the expression and its value for debugging
- Double the braces to print them literally: {{ }}