Advanced F-String Techniques
Complex Expression Handling
F-strings support sophisticated expressions and transformations beyond basic variable interpolation.
## Inline method calls and complex expressions
data = [1, 2, 3, 4, 5]
print(f"List sum: {sum(data)}, Average: {sum(data)/len(data):.2f}")
## Conditional logic within f-strings
score = 85
print(f"Performance: {'Excellent' if score >= 90 else 'Good' if score >= 75 else 'Average'}")
Debugging and Logging Techniques
## F-strings in debugging
def calculate_total(items):
total = sum(items)
print(f"Debug: items={items}, total={total}")
return total
Technique |
Syntax |
Example |
Width Specification |
{value:10} |
Right-aligned, 10 characters |
Precision Control |
{value:.2f} |
2 decimal places |
Type Conversion |
{value!r} |
Representation format |
Object Representation
## Custom object formatting
class LabExUser:
def __init__(self, name, role):
self.name = name
self.role = role
def __repr__(self):
return f"User(name={self.name}, role={self.role})"
user = LabExUser("Alice", "Developer")
print(f"User Details: {user!r}")
graph LR
A[F-String Input] --> B{Expression Parsing}
B --> C[Runtime Evaluation]
C --> D[String Interpolation]
D --> E[Final Output]
## Complex formatting scenarios
items = ['apple', 'banana', 'cherry']
print(f"Formatted List: {' | '.join(item.upper() for item in items)}")
Multi-line F-Strings
## Multi-line f-string with indentation
name = "LabEx"
description = f"""
Organization: {name}
Purpose: Technical Learning Platform
Features: Interactive Coding Environment
"""
print(description)
Error Handling Patterns
## Safe navigation and default values
def get_user_info(user=None):
return f"Username: {user.name if user else 'Unknown'}"
- Minimize complex logic within f-strings
- Precompute complex expressions
- Use f-strings for readability, not computation