def dynamic_formatting(value, width=10, precision=2):
return f"{value:{width}.{precision}f}"
print(dynamic_formatting(3.14159, width=15, precision=3))
print(dynamic_formatting(42.5, width=8, precision=1))
def complex_format(data):
return f"""
Name: {data['name']}
Status: {'Active' if data['active'] else 'Inactive'}
Score: {data['score']:05.2f}
"""
user_data = {
'name': 'LabEx Developer',
'active': True,
'score': 87.5
}
print(complex_format(user_data))
class FormattedOutput:
@staticmethod
def format_currency(amount, currency='$'):
return f"{currency}{amount:,.2f}"
@staticmethod
def format_percentage(value):
return f"{value:.2%}"
## Usage
print(FormattedOutput.format_currency(1234.56))
print(FormattedOutput.format_percentage(0.7532))
Technique |
Use Case |
Complexity |
Performance |
Basic F-Strings |
Simple formatting |
Low |
High |
Format Method |
Complex templates |
Medium |
Good |
Custom Classes |
Reusable formatting |
High |
Moderate |
graph TD
A[Input Data] --> B{Formatting Rules}
B -->|Simple| C[Direct F-String]
B -->|Complex| D[Custom Formatting Method]
D --> E[Formatted Output]
C --> E
from string import Template
def template_formatting():
template = Template('$name works at $company')
result = template.substitute(
name='LabEx Developer',
company='LabEx Platform'
)
return result
print(template_formatting())
import timeit
def performance_comparison():
## Comparing different formatting methods
f_string_time = timeit.timeit(
"f'{42:05d}'",
number=100000
)
format_time = timeit.timeit(
"'{:05d}'.format(42)",
number=100000
)
print(f"F-String Performance: {f_string_time}")
print(f"Format Method Performance: {format_time}")
performance_comparison()
- Use f-strings for most scenarios
- Implement custom formatting classes
- Leverage template-based formatting
- Optimize performance
- Handle complex formatting requirements
Key Takeaways
- Master advanced string formatting techniques
- Understand performance implications
- Create flexible, reusable formatting solutions
- Adapt formatting to specific use cases