Skip to Content

When f-strings win over .format / Template?

Category: Python Fundamentals

Answer

f-strings evaluate embedded expressions at runtime; .format is positional; Template is safe substitution. f-strings are the default for code (clean syntax, fast), but escape variables meant for end-users with Template to avoid template injection.

Concrete examples from the fca project context

Example 1

f"User {user.name} logged in at {datetime.now():%H:%M}" - fast, readable.

Example 2

Template(“Hello $user”).substitute(user=“Bob”) - safe for end-user-controlled input.

Example 3

.format(“{} {}”, a, b) - still useful for i18n message catalogs.

Example 4

Avoid %-formatting; legacy and ambiguous.

Data flow / flow chart

f"..."  -> default for code
  Template -> safe for user input
  .format  -> i18n catalogs

Takeaway

f-string default. Template when input is end-user. .format when i18n messages.