F-strings offer powerful formatting capabilities beyond simple variable interpolation. Mastering these techniques can significantly improve code readability and efficiency.
## Precision control
pi = 3.14159
print(f"Rounded Pi: {pi:.2f}") ## Output: 3.14
## Percentage formatting
ratio = 0.75
print(f"Completion: {ratio:.0%}") ## Output: 75%
## Padding and alignment
value = 42
print(f"Padded: {value:05d}") ## Output: 00042
Alignment and Width Techniques
Alignment |
Syntax |
Description |
Left |
{value:<10} |
Left-align with width 10 |
Right |
{value:>10} |
Right-align with width 10 |
Center |
{value:^10} |
Center-align with width 10 |
## Date and time formatting
from datetime import datetime
now = datetime.now()
print(f"Current time: {now:%Y-%m-%d %H:%M:%S}")
## Conditional formatting
score = 85
result = f"Performance: {'Excellent' if score > 90 else 'Good'}"
flowchart TD
A[Raw Value] --> B{Formatting Specifier}
B --> C[Width Control]
B --> D[Precision Control]
B --> E[Alignment Options]
C,D,E --> F[Formatted Output]
## Object representation
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"User(name={self.name}, age={self.age})"
user = User("LabEx", 25)
print(f"User Details: {user}")
- Use f-strings for most formatting needs
- Avoid complex logic within f-strings
- Leverage built-in formatting specifiers
- Consider readability over complexity
## Debugging f-string expressions
debug_value = 42
print(f"Debug: {debug_value=}") ## Python 3.8+
## Output: Debug: debug_value=42
Specifier |
Purpose |
Example |
d |
Integer |
{value:d} |
f |
Float |
{value:.2f} |
% |
Percentage |
{ratio:%} |
s |
String |
{text:s} |
By applying these formatting tips, developers can create more expressive and readable Python code with f-strings.