
You already use f-strings to put variables in text: f"Hello, {name}!" But f-strings are far more powerful than that. In this article, we’ll look at advanced f-strings and how You can control formatting directly inside the curly braces {} using a colon :.
1. Formatting Floats (Decimals)
This is the most common use. You want to control the number of decimal places. The syntax is :.{N}f where N is the number of decimal places.
my_pi = 3.14159265
print(f"Pi (2 decimals): {my_pi:.2f}")
# Output: Pi (2 decimals): 3.142. Padding and Alignment
Want to print a neat, aligned table? You can set the total width of a variable.
<: Left-align>: Right-align^: Center-align
item = "Apples"
price = 4.5
# Syntax: {variable : [fill_char][align][width]}
print(f"{item:<10} | ${price:>5.2f}")
# Output: Apples | $ 4.503. Number Formatting (Commas)
Want to show large numbers clearly?
big_number = 1234567890
print(f"Total: {big_number:,}")
# Output: Total: 1,234,567,8904. The “Self-Documenting” Debugger
This is the best trick of all. If you’re debugging, just add an equals sign = inside the brace.
user_name = "PythonProHub"
user_id = 9001
print(f"{user_name=} and {user_id=}")
# Output: user_name='PythonProHub' and user_id=9001It automatically prints the variable name and its value, saving you tons of typing!
Key Takeaways
- f-strings allow for advanced formatting beyond variable interpolation, using controls inside curly braces.
- You can format floats by specifying decimal places with the syntax :.{N}f.
- Alignment options like left (<), right (>), and centre (^) help format output neatly.
- Use commas for large number formatting to enhance clarity.
- Add an equals sign (=) in f-strings to create a ‘self-documenting’ debugger that shows variable names and values.





