Practical Examples
1. Data Logging and Reporting
class DataLogger:
def __init__(self, app_name):
self.app_name = app_name
def log_event(self, event_type, message):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"[{timestamp}] {self.app_name} - {event_type}: {message}"
print(log_entry)
## Usage example
logger = DataLogger("LabEx Platform")
logger.log_event("INFO", "User login successful")
def format_user_profile(name, age, skills):
formatted_skills = ", ".join(skills)
profile = f"""
User Profile:
Name: {name}
Age: {age}
Skills: {formatted_skills}
"""
return profile.strip()
## Example
user_skills = ["Python", "Docker", "Linux"]
print(format_user_profile("LabEx Student", 25, user_skills))
3. Financial Calculations
def format_currency(amount, currency="USD"):
return f"{currency} {amount:.2f}"
def calculate_discount(price, discount_rate):
discounted_price = price * (1 - discount_rate)
original = format_currency(price)
discounted = format_currency(discounted_price)
return f"Original: {original}, Discounted: {discounted}"
## Usage
print(calculate_discount(100.00, 0.2))
Scenario |
Formatting Technique |
Example |
Decimal Precision |
F-strings with .2f |
f"{value:.2f}" |
Percentage Display |
Multiplication and f-string |
f"{percentage * 100}%" |
Alignment |
String formatting methods |
"{:>10}".format(value) |
graph TD
A[Input Data] --> B{Formatting Requirements}
B --> |Simple Display| C[Basic F-Strings]
B --> |Complex Formatting| D[Advanced Formatting Methods]
B --> |Financial/Numeric| E[Precision Formatting]
C --> F[Output Display]
D --> F
E --> F
4. Configuration File Generation
def generate_config(app_name, version, debug_mode):
config_template = f"""
## LabEx Application Configuration
APP_NAME = "{app_name}"
VERSION = "{version}"
DEBUG_MODE = {str(debug_mode).lower()}
"""
return config_template.strip()
## Generate configuration
config = generate_config("Learning Platform", "2.1.0", True)
print(config)
5. Dynamic Template Rendering
def render_email_template(username, course_name, completion_date):
email_template = f"""
Dear {username},
Congratulations on completing the {course_name} course
on {completion_date}!
Best regards,
LabEx Team
"""
return email_template.strip()
## Example usage
email = render_email_template("Alice", "Python Fundamentals", "2023-06-15")
print(email)
Key Takeaways
- Choose formatting method based on complexity
- Use f-strings for readability
- Consider performance and Python version
- Practice different formatting scenarios
By mastering these practical examples, LabEx learners can effectively manipulate and format strings in various real-world programming contexts.