Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For most ordinary, local string construction, Python f-strings are the clearest default:

name = "Ada"
score = 97.5

message = f"{name} scored {score:.1f}%."

The value and its formatting rule appear beside the text that uses them. That improves readability, but interpolation is not the right tool for every context: logging, SQL, HTML, shell commands, and reusable templates have different requirements.

What string interpolation means

String formatting is the broader process of converting values into text. String interpolation specifically means placing computed values or expressions inside a text template.

user = "Mina"
message = f"Hello, {user}!"

Here, {user} is a replacement field. A field can contain an expression, a conversion such as !r, and a format specification such as :.2f. F-strings were introduced in Python 3.6 through PEP 498.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Why f-strings usually read best

Consider the same message written several ways:

name = "Ada"
language = "Python"

# Concatenation
message = "Hello, " + name + ". You are learning " + language + "."

# Percent formatting
message = "Hello, %s. You are learning %s." % (name, language)

# str.format()
message = "Hello, {}. You are learning {}.".format(name, language)

# Named str.format()
message = "Hello, {name}. You are learning {language}.".format(
    name=name, language=language
)

# f-string
message = f"Hello, {name}. You are learning {language}."

The f-string keeps each value next to the text it affects, avoids positional-argument mistakes, and removes boilerplate. This is the readability motivation described in PEP 498.

That advantage has a limit. Keep replacement fields simple and calculate substantial logic before building the message:

subtotal = price * quantity
total = subtotal * (1 + tax_rate)
summary = f"{quantity} items: ${total:.2f}"

This is generally easier to review and test than embedding the entire calculation in one field.

F-string syntax you can use every day

Variables, attributes, indexes, and calls

Put an f or F immediately before the opening quote. Expressions are evaluated where the string is created and may use attribute access, indexing, operators, and function calls.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
f"{user.name}"
f"{items[0]}"
f"{width * height}"
f"{len(records)} records"
f"{datetime.now():%Y-%m-%d}"

Use a named intermediate value when an expression becomes difficult to scan:

display_name = user.name.strip().title()
message = f"Welcome, {display_name}!"

Conversions

Conversions run before formatting:

value = "hellonworld"
f"{value!s}"  # str(value)
f"{value!r}"  # repr(value), showing escapes
f"{value!a}"  # ascii(value)

Use !s for normal display and !r when quotes and escape sequences help diagnose a value. A representation can expose sensitive information, so do not log secrets merely because !r is convenient.

Debug output with =

Python 3.8 added the debug specifier:

user_id = 42
status = "active"
print(f"{user_id=}, {status=}")
# user_id=42, status='active'

amount = 12.5
f"{amount=:.2f}"  # 'amount=12.50'

It is useful for temporary diagnostics, but f"{secret=}" can put credentials, tokens, or personal data into logs.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Formatting numbers, dates, and columns

F-strings use Python’s format-specification mini-language, documented at String — Common string operations.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Syntax Example Result or purpose
:.2f f"${price:.2f}" Two decimal places
:,.0f f"{population:,.0f}" Thousands separators and no decimal places
:.1% f"{completion:.1%}" Percentage presentation
:06d f"INV-{invoice_id:06d}" Zero-padded integer
:<10 f"{item:<10}" Left-aligned field of width 10
:>10 f"{item:>10}" Right-aligned field of width 10
:^10 f"{item:^10}" Centered field of width 10
:%B %d, %Y f"{today:%B %d, %Y}" Date formatting

Format specifications can contain nested replacement fields:

value = 3.14159265
precision = 3
f"{value:.{precision}f}"  # '3.142'

width = 12
f"{value:{width}.{precision}f}"

Name controlling values such as width and precision; avoid deeply nested expressions.

Braces, multiline output, and whitespace

Literal braces

Single braces mark replacement fields. Double them when the output must contain a literal brace:

name = "Ada"
f"{{name}} = {name}"
# '{name} = Ada'

f"Dictionary syntax: {{key: value}}"

This matters for JSON-like examples, configuration snippets, mathematical notation, sets, and code samples.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Long and multiline strings

Adjacent literals inside parentheses keep each output line visible without backslash continuation:

name = "Ada"
role = "developer"

message = (
    f"Name: {name}n"
    f"Role: {role}n"
    "Status: active"
)

Triple-quoted f-strings work for larger blocks:

message = f"""
Hello, {name}.

Your account is ready.
""".strip()

Check for unintended indentation or leading and trailing newlines. A large template may be clearer in a dedicated templating system.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Python version boundaries

Feature Availability Practical implication
F-strings Python 3.6+ Use them only when your supported versions include 3.6 or newer.
await and async for in fields Python 3.7+ Relevant when expressions are asynchronous.
Debug specifier = Python 3.8+ Older interpreters need another diagnostic form.
Relaxed f-string grammar Python 3.12+ Nested same-quote strings, comments, backslashes, and multiline expressions are permitted.
T-strings Python 3.14+ They create structured template objects, not ordinary strings.

Python 3.12’s grammar changes are described in What’s New in Python 3.12 and formalized by PEP 701. Code using those relaxed rules is not portable to earlier versions. For broad compatibility, choose quote styles that work on your minimum supported interpreter:

items = {"name": "Ada"}
f"{items['name']}"

How the alternatives differ

str.format()

name = "Ada"
message = "Hello, {name}!".format(name=name)

REPORT_LINE = "{label:<20} {value:>10.2f}"
line = REPORT_LINE.format(label="Revenue", value=1250.5)

Use str.format() when a template is stored separately, reused, or must support Python versions before 3.6. It supports named and positional fields and the same broad format-specification system, but is more verbose and does not allow arbitrary expressions in fields the way f-strings do.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Percent formatting

name = "Ada"
message = "Hello, %s!" % name

record = {"name": "Ada", "role": "developer"}
message = "%(name)s is a %(role)s." % record

Percent formatting remains valid in legacy code and is important at logging call sites. For new ordinary application strings, it is usually less expressive and offers more opportunities for tuple, placeholder-count, and type mistakes.

string.Template

from string import Template

template = Template("Hello, $name!")
message = template.substitute(name="Ada")

Template("${noun}ification is useful").substitute(noun="class")
# 'classification is useful'

Template deliberately limits placeholders to $identifier and ${identifier}. That can suit user-editable or translation-oriented templates where arbitrary Python expressions would be undesirable. substitute() raises KeyError for missing values. safe_substitute() leaves missing or malformed placeholders in the result; “safe” here means it avoids some exceptions, not that it validates output or makes it secure. See the string module documentation.

T-strings in Python 3.14+

A t-string uses a t prefix:

name = "Ada"
template = t"Hello, {name}!"

Unlike an f-string, it does not immediately return a combined str. It produces a string.templatelib.Template containing literal segments and interpolation objects, conceptually accessible through attributes such as strings, interpolations, and values. A custom processor can inspect those parts, apply context-aware escaping, and then render them.

T-strings are an enabling mechanism, not an automatic security guarantee. Their safety depends on the trusted processor that handles the template, as explained in PEP 750. They are unrelated to the older string.Template class.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Logging is a deliberate exception

Pass the message template and values separately to a logger:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
logger.info("User %s logged in", username)

logger.debug(
    "Fetched %d records for user %s",
    len(records),
    user_id,
)

This lets the logging framework defer message construction when a level is disabled and keeps the values available separately to the logging machinery. Converting the call to an f-string changes that evaluation behavior:

logger.info(f"User {username} logged in")

Do not confuse three layers:

  1. The logger call receives a message template and arguments.
  2. The LogRecord combines them using the logging message convention.
  3. logging.Formatter(style=...) controls the output layout and may use %, {, or $ styles.

The formatter’s style does not change how arguments passed to logger.info(), logger.debug(), and related methods are supplied. See Python’s logging documentation. Structured logging should put searchable fields in structured attributes instead of encoding every value into prose.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Where interpolation is the wrong tool

SQL

Never treat an f-string as SQL escaping:

# Unsafe
query = f"SELECT * FROM users WHERE name = '{name}'"

Use the database driver’s parameterized interface. Placeholder syntax differs by driver, so follow that driver’s documentation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cursor.execute(
    "SELECT * FROM users WHERE name = ?",
    (name,),
)

The f-string only creates text; it does not understand SQL syntax.

HTML

# Unsafe when user_input is untrusted
html = f"<p>{user_input}</p>"

Escape according to the output context or use a trusted HTML templating system. HTML escaping rules differ for text, attributes, URLs, JavaScript, and CSS.

Shell commands

Do not build a command line by interpolating untrusted arguments:

# Avoid constructing a shell command string
command = f"grep {user_pattern} {filename}"

Prefer an argument-list API and configure shell behavior deliberately:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
import subprocess

subprocess.run(
    ["grep", user_pattern, filename],
    check=True,
)

Safety still depends on the platform, executable, API options, and whether a shell is involved.

JSON, URLs, and other structured data

Presentation text is not a serializer. Use format-aware APIs:

import json

payload = json.dumps({"name": name, "score": score})

Use URL builders, path APIs, serializers, parameterized queries, and context-specific escaping where available.

Common mistakes and their fixes

Forgetting the prefix

name = "Ada"
message = "Hello, {name}!"
# 'Hello, {name}!'

Without f, braces are ordinary characters.

Accidental eager evaluation

f"Result: {expensive_operation()}"

The function runs immediately. This matters in diagnostics and logging; defer work with a level check or the logging API’s argument form when appropriate.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Missing values

"Hello, {name}".format()
# KeyError: 'name'

The equivalent Template.substitute() call also raises KeyError. Use explicit validation rather than relying on safe_substitute() to conceal mistakes.

Side effects inside fields

message = f"Saved {save_record(record)}"

Perform the operation first, then interpolate its result. String construction should not hide a side effect.

Overly complex replacement fields

is_active = bool(user and user.profile and user.profile.active)
status = "active" if is_active else "inactive"
message = f"Account status: {status}"

Named decisions are easier to test than a long conditional embedded in a message.

A practical choice guide

Situation Preferred approach Why
Local human-facing message F-string Values and formatting stay visible at the point of use.
Number or date formatting F-string Format rules sit beside the value.
Template stored separately str.format() or Template Data can be supplied later.
User-editable simple template string.Template Restricted $name syntax is easy to expose.
Legacy Python before 3.6 .format() or % F-strings are unavailable.
Logging call Logger template plus arguments Preserves logging’s deferred message handling.
SQL values Parameterized query Separates data from SQL syntax.
HTML output Context-aware escaping or templating Escaping depends on the HTML context.
Shell arguments Argument-list process API Avoids constructing a shell command string.
JSON or another structured format Dedicated serializer Correctly escapes and encodes values.
Custom processing before rendering T-string and a trusted processor on Python 3.14+ Preserves literal and interpolation structure.
Complex business logic Compute first, interpolate second Keeps the string declarative and testable.

Readability checklist

  • Is this text for a person, or will another parser interpret it?
  • Are replacement expressions short enough to scan?
  • Have calculations and business decisions been named and tested first?
  • Are precision, alignment, dates, and other output requirements explicit?
  • Could !r, debug output, or a value itself expose sensitive data?
  • Does the project’s minimum Python version support the syntax used?
  • Would a serializer, parameterized API, escaping library, or argument-list API be safer?
  • For logging, are the template and arguments passed separately?

Bottom line

Adopt f-strings as the default for clear, local string construction, not as a universal replacement for every formatting API. Keep fields simple, format output contracts explicitly, and calculate complex values before interpolation. Preserve logger argument formatting, use reusable templates when the template is data, and choose parameterization, escaping, serialization, or a trusted t-string processor whenever the resulting text will be interpreted by another system.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.