F-strings (formatted string literals) have transformed string formatting in Python since their introduction in Python 3.6. Let’s explore some useful ways to use f-strings.
1. Number Formatting
Decimal Places
When working with floating-point numbers, controlling decimal places is crucial for readability:
ratio = 0.8544
print(f'{ratio:.2f}') # Output: 0.85
Large Numbers
Make big numbers readable with automatic comma separation:
num = 100000000
print(f"{num:,}") # Output: 100,000,000
2. Percentage Formatting
Converting decimals to percentages is a common task in data analysis and reporting:
ratio = 0.8544
print(f"{ratio:.1%}") # Output: 85.4%
3. Date and Time Formatting
F-strings make date formatting intuitive and readable:
from datetime import datetime
date = datetime(2022, 1, 1, 15, 30, 45)
print(f"{date:%I:%M %p} on {date:%A}") # Output: 03:30 PM on Saturday
4. Debug Printing
One of the most useful features for debugging is the ability to display variable names alongside their values:
for i in range(3):
print(f"{i=}")
# Output:
# i=0
# i=1
# i=2