How to Format Numbers in Python f-Strings Easily
Use
f"{value:format_spec}" to format numbers in Python f-strings. The format_spec controls decimal places, padding, alignment, and more, like .2f for two decimals or , for thousand separators.Syntax
The basic syntax to format numbers in an f-string is f"{value:format_spec}". Here, value is the number you want to format, and format_spec defines how the number appears.
- Decimal places: Use
.nfwherenis the number of decimals (e.g.,.2ffor two decimals). - Thousands separator: Use
,to add commas (e.g.,,). - Padding and alignment: Use width and alignment symbols like
10for width,<for left-align,>for right-align.
python
value = 1234.5678 formatted = f"{value:,.2f}" print(formatted)
Output
1,234.57
Example
This example shows formatting a float number with two decimal places and a comma as a thousands separator.
python
price = 1234567.89123 formatted_price = f"${price:,.2f}" print(formatted_price)
Output
$1,234,567.89
Common Pitfalls
Common mistakes include forgetting the colon : before the format specifier or using incorrect format codes that cause errors.
Also, using f"{value:.2}" without specifying f for float formatting will not limit decimals.
python
# Wrong: missing colon value = 123.456 # print(f"{value.2f}") # SyntaxError # Correct: print(f"{value:.2f}") # prints 123.46
Output
123.46
Quick Reference
| Format Specifier | Description | Example |
|---|---|---|
| .2f | Two decimal places float | f"{3.14159:.2f}" → 3.14 |
| , | Thousands separator | f"{1000000:,}" → 1,000,000 |
| 10 | Width 10, right aligned | f"{42:10}" → ' 42' |
| <10 | Width 10, left aligned | f"{42:<10}" → '42 ' |
| ^10 | Width 10, centered | f"{42:^10}" → ' 42 ' |
| e | Scientific notation | f"{1000:e}" → 1.000000e+03 |
Key Takeaways
Use f-strings with a colon and format specifier to control number formatting.
Common format specs include .nf for decimals, , for thousands separator, and width/alignment symbols.
Always include the colon before the format specifier to avoid syntax errors.
Test formatting with print to see the exact output before using in your program.
Use the quick reference table to remember common format specifiers.