F-strings are convenient for simple string interpolation, but they are tightly coupled with the surrounding Python code. They are typically used for a single, specific task.
metrics = {
'accuracy': 0.95,
'precision': 0.88,
'recall': 0.92,
'f1_score': 0.89,
'auc_roc': 0.93,
'specificity': 0.87
}
metrics_str = ""
for metric, value in metrics.items():
if value > 0.9:
metrics_str += f"{metric}: {value:.3f} (Excellent)\n"
else:
metrics_str += f"{metric}: {value:.3f} (Needs Improvement)\n"
print(metrics_str)
accuracy: 0.950 (Excellent)
precision: 0.880 (Needs Improvement)
recall: 0.920 (Excellent)
f1_score: 0.890 (Needs Improvement)
auc_roc: 0.930 (Excellent)
specificity: 0.870 (Needs Improvement)
Jinja’s templating engine is more versatile and powerful. It allows you to define templates with placeholders for dynamic data and supports conditionals, loops, and reuse across multiple contexts.
Use Jinja to perform complex templating tasks or generate dynamic reports.
# Jinja template version
from jinja2 import Template
template = Template("""
{% for metric, value in metrics.items() %}
{% if value > 0.9 %}
{{ metric }}: {{ value | round(3) }} (Excellent)
{% else %}
{{ metric }}: {{ value | round(3) }} (Needs Improvement)
{% endif %}
{% endfor %}
""")
result = template.render(metrics=metrics)
print(result)
accuracy: 0.95 (Excellent)
precision: 0.88 (Needs Improvement)
recall: 0.92 (Excellent)
f1_score: 0.89 (Needs Improvement)
auc_roc: 0.93 (Excellent)
specificity: 0.87 (Needs Improvement)