## Currency formatting
price = 1234.56
print(f"Price: ${price:,.2f}") ## Adds comma separators
## Percentage representation
ratio = 0.75
print(f"Completion: {ratio:.1%}") ## 75.0%
## Scientific notation
large_number = 1000000
print(f"Scientific: {large_number:e}")
Structured Log Messages
def create_log_entry(level, message):
timestamp = "2023-06-15 10:30:45"
return f"[{timestamp}] [{level:^7}] {message}"
print(create_log_entry("ERROR", "Database connection failed"))
print(create_log_entry("INFO", "Service started successfully"))
3. Configuration and Template Strings
Dynamic Configuration Rendering
class ConfigFormatter:
def __init__(self, **kwargs):
self.config = kwargs
def render(self, template):
return template.format(**self.config)
config = ConfigFormatter(
username="labex_user",
database="python_projects",
port=5432
)
connection_string = "postgresql://{username}@localhost:{port}/{database}"
print(config.render(connection_string))
4. Complex Data Representation
class User:
def __init__(self, name, age, role):
self.name = name
self.age = age
self.role = role
def __str__(self):
return f"User(name={self.name}, age={self.age}, role={self.role})"
user = User("LabEx Developer", 28, "Engineer")
print(user)
Dynamic Styling
def format_status(status, value):
colors = {
'success': '\033[92m', ## Green
'warning': '\033[93m', ## Yellow
'error': '\033[91m' ## Red
}
reset = '\033[0m'
return f"{colors.get(status, '')}{value}{reset}"
print(format_status('success', "Operation completed"))
print(format_status('error', "Critical failure"))
flowchart TD
A[Input Data] --> B{Formatting Requirements}
B --> |Simple| C[Basic Formatting]
B --> |Complex| D[Advanced Techniques]
C --> E[Output Presentation]
D --> E
| Technique |
Use Case |
Performance |
Readability |
| F-strings |
Dynamic Values |
High |
Excellent |
.format() |
Complex Templating |
Moderate |
Good |
| %-formatting |
Legacy Systems |
Low |
Poor |
Recommendations
- Use f-strings for most scenarios
- Implement clear, consistent formatting
- Consider performance for large-scale operations
- Leverage Python's formatting capabilities
def safe_format(template, **kwargs):
try:
return template.format(**kwargs)
except KeyError as e:
return f"Formatting Error: Missing {e} parameter"
## Example usage
template = "Hello, {name}! You are {age} years old."
print(safe_format(template, name="LabEx")) ## Handles missing parameters
Conclusion
Mastering Python's string formatting techniques empowers developers to create more readable, maintainable, and efficient code. By understanding these practical techniques, you can transform how you handle text representation in your Python projects.