Practical Examples
Real-World String Insertion Scenarios
1. User Profile Generation
def create_user_profile(name, age, city):
profile = f"""
User Profile:
--------------
Name: {name}
Age: {age}
City: {city}
"""
return profile
## Example usage
user_info = create_user_profile("LabEx Developer", 28, "San Francisco")
print(user_info)
import datetime
def generate_log_entry(level, message):
timestamp = datetime.datetime.now()
log_format = f"[{timestamp:%Y-%m-%d %H:%M:%S}] [{level.upper()}]: {message}"
return log_format
## Demonstration
error_log = generate_log_entry("error", "Database connection failed")
print(error_log)
3. CSV Data Processing
def format_csv_row(name, score, passed):
status = "Pass" if passed else "Fail"
return f"{name},{score},{status}"
## Batch processing
students = [
("Alice", 85, True),
("Bob", 45, False),
("Charlie", 72, True)
]
csv_rows = [format_csv_row(name, score, passed) for name, score, passed in students]
print("\n".join(csv_rows))
4. Dynamic Template Generation
def create_email_template(name, product, discount):
template = f"""
Dear {name},
We're excited to offer you a special {discount}% discount
on our latest {product} at LabEx!
Don't miss this incredible opportunity!
Best regards,
LabEx Marketing Team
"""
return template
## Example
promo_email = create_email_template("Python Developer", "Online Course", 25)
print(promo_email)
Formatting Method |
Use Case |
Complexity |
Performance |
% Operator |
Simple replacements |
Low |
Fastest |
.format() |
Moderate complexity |
Medium |
Moderate |
f-Strings |
Complex formatting |
High |
Slower |
def safe_format(template, **kwargs):
try:
return template.format(**kwargs)
except KeyError as e:
return f"Missing parameter: {e}"
## Safe formatting
safe_template = "Hello, {name}! Your score is {score}."
result = safe_format(safe_template, name="Developer")
print(result)
Mermaid Flow of String Insertion
graph TD
A[Raw String Template] --> B{Formatting Method}
B --> C[Insert Variables]
C --> D[Validate Data]
D --> E[Generate Formatted String]
E --> F[Output/Use String]
import sys
def format_cli_output(command, exit_code):
status = "Successful" if exit_code == 0 else "Failed"
return f"Command '{command}' execution: {status} (Exit Code: {exit_code})"
## Simulated CLI output
cli_result = format_cli_output(sys.argv[0], 0)
print(cli_result)
Key Takeaways
- String formatting is versatile and powerful
- Choose the right technique for your specific use case
- Consider readability and performance
- Always validate and handle potential formatting errors