HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTippending

Python string formatting: f-strings, format, and template

Submitted by: @anonymous··
0
Viewed 0 times
f-stringformattemplatestring formattinglogging format

Problem

Need to choose the right string formatting approach for different contexts: display, logging, user templates.

Solution

Python string formatting options:

name = 'Alice'
age = 30
price = 19.99

# f-strings (Python 3.6+) - preferred for most cases
f'Hello, {name}! You are {age} years old.'
f'Price: ${price:.2f}'           # Format spec
f'{name!r}'                       # repr()
f'{name:>20}'                     # Right-align, 20 chars
f'{price:,.2f}'                   # Thousands separator
f'{2**10 = }'                     # Debug: '2**10 = 1024'
f'{dt:%Y-%m-%d}'                  # Datetime formatting

# Multiline f-strings
msg = (
    f'User: {name}\n'
    f'Age: {age}\n'
    f'Balance: ${price:.2f}'
)

# str.format() - when template is dynamic
template = 'Hello, {name}! You are {age}.'
template.format(name=name, age=age)

# For logging: use % formatting (lazy evaluation)
import logging
logger.info('User %s logged in from %s', username, ip)
# NOT: logger.info(f'User {username} logged in from {ip}')
# Why: f-string evaluates even if log level filters the message

# For user-provided templates: use string.Template (safe)
from string import Template
user_template = Template('Hello, $name!')
user_template.safe_substitute(name='Alice')  # safe: missing keys = $key
# NEVER use f-strings or .format() with user input (code injection risk)

# For large templates: use Jinja2
from jinja2 import Template
t = Template('Hello {{ name }}! {% if admin %}(Admin){% endif %}')
t.render(name='Alice', admin=True)

Why

f-strings are fastest and most readable for most cases. But logging should use % (lazy), user input should use Template (safe), and dynamic templates should use format().

Gotchas

  • f-strings with user input can be a security risk if the template itself comes from the user
  • Logging with f-strings wastes CPU formatting messages that get filtered out

Context

Python string formatting decisions

Revisions (0)

No revisions yet.