Python String Formatting Methods Compared | Generated by AI

Home 2026.04

Question: When formatting a string in Python, which method is better?

Answer:

It depends on what you care about (readability, performance, logging, compatibility). There is no single “best” universally, but in modern Python, there is a clear default choice.


1. The modern best choice: f-strings (✅ recommended)

name = "Alice"
age = 25
msg = f"{name} is {age} years old"

Why this is best:

f"{name.upper()} is {age + 1} next year"

👉 This is the default choice in Python 3.6+


2. .format() (older, flexible, but less used now)

msg = "{} is {} years old".format(name, age)

or:

msg = "{name} is {age}".format(name=name, age=age)

Pros:

Cons:

👉 Today: mostly legacy / compatibility use


3. % formatting (old style)

msg = "%s is %d years old" % (name, age)

Pros:

Cons:

👉 Use it only for logging, not general string formatting.


4. String concatenation (+)

msg = name + " is " + str(age) + " years old"

Cons:

👉 Avoid in almost all cases.


5. Performance comparison (rough intuition)

Fastest → Slowest (usually):

f-string  ≥  % formatting  >  .format()  >  concatenation

But differences are small unless in tight loops.


6. Important exception: logging

Even though f-strings are best generally:

logging.info(f"User {name}")   # ❌ not ideal

Use:

logging.info("User %s", name)  # ✅ correct

Because logging uses lazy formatting.


7. Final recommendation

Use this rule:


8. Simple intuition


If you want, I can show edge cases where .format() is still better than f-strings (there are a few subtle ones).


Back Donate