If you are still formatting strings in Python using .format() or the + operator, we need to talk. 😅
F-strings (formatted string literals) were introduced in Python 3.6, and they are the cleanest way to inject variables into text. But most developers only use them for the basics.
Here are 3 F-string tricks that will instantly make your code look more professional:
1. Formatting Numbers with Commas
Have a large number and want to make it readable? You don't need to import a library.
revenue = 1234567.89
print(f"Total revenue: ${revenue:,.2f}")
2. Debugging with the = Operator (Python 3.8+)
This is my absolute favorite. You no longer have to write print(f"x: {x}"). Just add an equals sign inside the curly braces, and Python will print the expression and the result.
x = 10
y = 20
print(f"{x + y = }")
3. Text Alignment (Perfect for CLI tools)
If you are building a command-line app and want your text to line up perfectly, you can use <, >, and ^ to align left, right, or center.
name = "Python"
print(f"{name:^20}")
The Takeaway:
F-strings are powerful. Mastering these little tricks saves you from writing messy code and makes your scripts much easier to read.
Top comments (0)