class LabExScore:
def __init__(self, value):
self.value = value
def __format__(self, format_spec):
if format_spec == 'grade':
if self.value >= 90:
return 'Excellent'
elif self.value >= 80:
return 'Good'
else:
return 'Needs Improvement'
return str(self.value)
score = LabExScore(95)
print(f"Student Performance: {score:grade}")
def dynamic_format(data, width=10):
return f"{data:^{width}}"
courses = ['Python', 'JavaScript', 'Data Science']
for course in courses:
print(dynamic_format(course))
Dictionary Unpacking
user = {
'name': 'LabEx Developer',
'age': 5,
'skills': ['Python', 'Data Analysis']
}
print("User Profile: {name}, {age} years old".format(**user))
print(f"Skills: {', '.join(user['skills'])}")
flowchart TD
A[Formatting Performance] --> B[f-strings]
A --> C[.format() Method]
A --> D[%-formatting]
B --> E[Fastest]
C --> F[Moderate]
D --> G[Slowest]
Technique |
Complexity |
Readability |
Performance |
%-formatting |
Low |
Poor |
Slow |
.format() |
Medium |
Good |
Moderate |
f-strings |
High |
Excellent |
Fast |
def safe_format(template, **kwargs):
try:
return template.format(**kwargs)
except KeyError as e:
return f"Missing format parameter: {e}"
## Example usage
print(safe_format("Hello {name}", name="LabEx"))
print(safe_format("Hello {username}"))
class ComplexFormatter:
def __format__(self, format_spec):
if format_spec == 'tech':
return f"LabEx Tech Formatter: {self}"
return str(self)
obj = ComplexFormatter()
print(f"{obj:tech}")
import logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s: %(message)s',
level=logging.INFO
)
logging.info(f"LabEx tutorial on advanced formatting")
Best Practices
- Use f-strings for most formatting needs
- Implement custom
__format__()
method for complex objects
- Consider performance for large-scale formatting
- Handle potential formatting errors gracefully
By mastering these advanced techniques, you'll become a more sophisticated Python developer with LabEx's comprehensive learning resources.