🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python String Formatting: f-strings, format, Templates

Python StringsđŸŸĸ Free Lesson

Python String Formatting: f-strings, format, Templates

Python has four ways to build a string from values, and the differences are practical rather than decorative. F-strings evaluate expressions in place and are the default for code you control. The format method separates the template from the data, which matters when the template comes from configuration. Percent formatting survives in logging setups and older codebases. string.Template deliberately restricts what a template can do, which makes it the right choice when the template comes from a user.

Underneath three of those four sits the same format specification, a compact mini-language that controls width, alignment, precision, and numeric presentation. Learning it once means every formatting call becomes predictable, whether the value arrived through an f-string or through format.

What You'll Learn

  • 1Read and write format specifications for numbers, strings, and dates
  • 2Choose between f-strings, format, percent, and Template by the source of the template
  • 3Use debug f-strings and conversions to make diagnostics faster to write
  • 4Recognize the security and locale limits of each approach

The format specification, shared by everything

The grammar after the colon is fill and alignment, sign, zero padding, width, separator, precision, and type, each optional and each position-sensitive. Numbers default to general presentation, strings default to alignment, and precision applies to the number of digits after the decimal point for floats or the maximum characters for strings.

python
value = 1234.5678
name = "ada"

f"{value:.2f}"          # '1234.57'  two decimals
f"{value:10.2f}"        # '   1234.57' width 10
f"{value:0>10.2f}"      # '0001234.57' zero fill, right aligned
f"{value:,}"            # '1,234.5678' thousands separators
f"{value:.2%}"          # '123456.78%' treated as a proportion
f"{-value:+.2f}"        # '-1234.57' explicit sign
f"{name:^9}"            # '   ada   ' centered
f"{name:*^9}"           # '***ada***' custom fill character
f"{255:x}"              # 'ff' hexadecimal
f"{255:b}"              # '11111111' binary
f"{0.12345:.3e}"        # '1.234e-01' scientific

The alignment characters are left, right, and center, and the default for strings is left while the default for numbers is right. That default is why numbers line up in columns without any explicit specification and why strings do not. Setting fill without alignment is a common mistake: the fill character only takes effect once an alignment character is also present.

F-strings: expressions, conversions, and debugging

F-strings evaluate whatever appears inside the braces at call time and interpolate the result. The expression space is a full Python expression, which means method calls, arithmetic, conditional expressions, and even dictionary lookups all work. Two features make them especially productive in day-to-day code: conversion flags, which force a representation, and the equals sign, which prints the expression alongside its value.

python
price = 19.99
qty = 3
customer = {"name": "ada", "tier": "gold"}

f"{price * qty:.2f}"
f"{customer['name'].upper():<12}"
f"{price!r}"                       # repr, useful for debugging strings
f"{price=}, {qty=}, {price * qty=}"  # x=19.99, qty=3, total
f"{'quoted':>10}"
f"{qty:,d}" if hasattr(qty, "__index__") else str(qty)

nested = {"a": [1, 2, {"b": 3}]}
f"{nested['a'][2]['b']}"

Nested quotes stop being a problem in Python 3.12 and later, where the same quote type can appear inside the braces. On earlier versions the standard workaround is to use a different quote for the outer string or to assign the inner value to a temporary name before interpolation. The debug equals sign is the single biggest quality-of-life feature: a failing assertion or a log line can print every variable in one line without repeating each name twice.

str.format: templates you can separate from data

str.format exists because sometimes the template is data. Reports, localized messages, and configuration-driven layouts are built from strings that arrive at runtime, and f-strings cannot be used when the expression is not written in your source file. Named arguments, numbered arguments, and attribute or index access on a single argument cover most real cases.

python
template = "{name} bought {qty} {product} at {price:.2f}"
template.format(name="ada", qty=3, product="widget", price=19.99)

"{0} {1} {0}".format("spam", "eggs")

class Invoice:
    def __init__(self, number, total):
        self.number = number
        self.total = total

bill = Invoice("INV-42", 1250.0)
"invoice {0.number} total {0.total:,.2f}".format(bill)

data = {"id": 7, "sku": "W-1"}
"{id} {sku}".format(**data)

Reusing position zero is the clean way to repeat a value without computing it twice. Passing a whole object and reaching into its attributes or items keeps the template readable when the data is hierarchical. The cost of format is a small amount of speed relative to f-strings, which matters only in hot loops formatting thousands of lines.

Percent formatting: legacy you must still read

The percent operator predates both f-strings and format, and it remains visible in logging configuration, older libraries, and C-style documentation. The mapping is fixed: %s for strings, %d for integers, %f for floats with an optional precision, and %(name)s when the right-hand side is a dictionary.

python
"%s bought %d units at %.2f" % ("ada", 3, 19.99)
"%(name)s <%(email)s>" % {"name": "ada", "email": "[email protected]"}
"%10.2f|%-10s|" % (3.14159, "left")

New code should not use percent formatting. It is kept here because you will encounter it, and because mixing the percent sign with a literal one requires doubling it, which is a recurring source of confusion in format strings that contain progress percentages.

string.Template: safe substitution for untrusted input

When the template comes from a user or from an uploaded file, evaluating expressions is unacceptable. string.Template accepts only $identifier placeholders and performs no evaluation at all, so an injected brace or an attempted expression cannot execute anything. safe_substitute leaves unknown placeholders untouched rather than raising, which is what you want when a message has optional segments.

python
from string import Template

greeting = Template("hello $name, your balance is $balance")
print(greeting.substitute(name="ada", balance="$1,200.00"))

partial = Template("$greeting, $name")
print(partial.safe_substitute(greeting="hi", name="ada"))

dollar = Template("price $$9.99")
print(dollar.substitute())

Double dollars escape a literal dollar sign, which is the template equivalent of percent-percent in the older scheme. Because the class is part of the standard library and has no evaluation step, it is the safest default for email bodies and other externally supplied templates.

Dates, enums, and objects in format specifications

The specification language is not limited to numbers and strings. Objects that define their own formatting protocol can be given a specification directly, which is how a date object accepts a layout such as year, month, and day without any conversion function in sight. Enums format through their name or their value depending on the conversion flag, so a diagnostic line can print either the symbolic label the developer wrote or the integer the wire format carries.

python
from datetime import datetime
from enum import Enum


class Level(Enum):
    DEBUG = 10
    INFO = 20


stamp = datetime(2026, 3, 14, 9, 30)
f"{stamp:%Y-%m-%d %H:%M}"
f"{Level.INFO}"
f"{Level.INFO.value:d}"

The percent inside the braces is the date format language, a separate mini-language with its own directives, and mixing it up with the numeric specification is a frequent source of confusion. Remember the split: before the colon is the value's own specification, and for a date that specification is a date layout. For everything else, the shared grammar of fill, alignment, width, and precision applies, and objects opt in only if they implement the hook that reads it.

Choosing among the four

The choice collapses to one question: who wrote the template. If you did, in source code you control, use an f-string. If the template is stored or configured but trusted, use format. If the template might come from outside the trust boundary, use Template. Percent formatting is for reading existing code and for the logging module's own formatting style.

ApproachTemplate sourceEvaluates expressionsTypical use
F-stringSource codeYesEveryday interpolation and logging
str.formatConfig or codeThrough accessorsReports, reusable templates
% operatorCode, legacyNoOld code, logging formats
string.TemplateUntrusted inputNoUser-supplied templates

For performance-sensitive loops, remember that the template is parsed on every call regardless of which approach you choose. Building the format pieces once, or formatting a batch of values in a single comprehension, will usually matter more than the choice between f-strings and format.

Common Mistakes

Setting a fill character without an alignment flag

Fix: Write fill, alignment, and width together, such as asterisk, caret, and nine, or the fill is ignored

Using an f-string when the template arrives from configuration

Fix: Use str.format or string.Template, because only they accept a template built at runtime

Feeding user-supplied templates to format or an f-string

Fix: Use string.Template with substitute, which performs no expression evaluation at all

Formatting a percentage with the percent type without scaling

Fix: Multiply by one hundred yourself or use the percent format specifier, which multiplies by one hundred automatically

Best Practices

  • Default to f-strings in code you own and reserve format for stored templates
  • Learn the format specification once; it applies to f-strings and format identically
  • Use the debug equals sign liberally in throwaway diagnostics
  • Prefer string.Template for anything an external party can influence
  • Batch formatting in a comprehension rather than concatenating inside a hot loop

Interview Questions

Q1: What is the difference between the exclamation conversions r, s, and a?

r produces the repr of the value, s produces the str, and a produces the ASCII-safe repr, escaping non-ASCII characters. repr is usually what you want in diagnostics because it shows quotes around strings.

Q2: Why does setting a fill character alone do nothing?

The fill character is only recognized when an alignment character follows it. Without an alignment flag, the first character is interpreted as the alignment itself, and the width applies with the default alignment.

Q3: When is string.Template preferable to an f-string?

When the template string is not written in your source, especially when it can be supplied by a user. Template performs substitution only and cannot evaluate expressions, so it is safe against injection.

Key Takeaways

  • One format specification drives f-strings, format, and percent formatting
  • Alignment defaults differ: right for numbers, left for strings
  • Debug f-strings with the equals sign make diagnostics one-liners
  • str.format separates template from data; percent formatting is legacy
  • string.Template is the safe choice for templates you did not write
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement