1. Home
  2. Blog
  3. Software Development

Software Development

Python f-strings Explained: Formatting Numbers, Dates and Debug Output

f-strings are the clearest way to build text in Python. Learn the format codes for money, percentages, padding and dates, the handy debug shortcut, and the traps worth knowing, with every example run.

9 min read
Python f-strings explained: formatting numbers, dates and debug output

Key takeaways

  • An f-string is a string with an f prefix, where anything in {} is evaluated as Python code.
  • After a colon, a format specifier controls decimals, separators, width, alignment and dates.
  • {value=} prints both the expression and its value, which is ideal for quick debugging.
  • Do not use f-strings to build SQL queries or to format untrusted templates.

Building a line of text from variables used to mean a tangle of + signs and str() calls. Since Python 3.6, f-strings let you write the text as it should look and drop the values straight into it. They are short, readable and, in our timing test, among the fastest options.

Every example below was run with Python 3.13, and the output shown is what we got.

What is an f-string?

An f-string, or formatted string literal, is a normal string with the letter f (or F) in front. Inside it, curly braces mark expressions. Python evaluates each one when the line runs and inserts the result as text.

The expressions are real Python, so you can do arithmetic, call functions, index lists or read dictionary keys directly inside the braces.

Basic syntax

name, price, qty = "Asha", 1234.5, 3
print(f"{name} bought {qty} items for {price * qty}")
# Asha bought 3 items for 3703.5

items = {"pen": 10}
print(f"{items['pen']}")
# 10

Notice the inner quotes in the second example. The f-string uses double quotes, so the dictionary key uses single quotes. Since Python 3.12 you can even reuse the same quote type inside the braces, but mixing them is still easier to read and works on older versions.

The format specifier

Add a colon after the expression to control how it is shown. The part after the colon follows Python’s format mini-language, which has this general shape:

{value:[fill][align][sign][width][grouping][.precision][type]}

You rarely need all of it. Most real formatting uses one or two pieces, such as :.2f for two decimal places or :>10 to right-align in ten characters. The same mini-language is used by str.format() and the built-in format() function, so what you learn here works there too.

Formatting numbers

price = 1234.5
print(f"{price:.2f} | {price:,.2f}")
# 1234.50 | 1,234.50

print(f"{0.4567:.1%} | {42:05d} | {255:x} {255:X} {255:o} {255:b} | {255:#x}")
# 45.7% | 00042 | ff FF 377 11111111 | 0xff

print(f"{1234567:_} | {-5:+d} {5:+d}")
# 1_234_567 | -5 +5

print(f"{1/3:.3g} {123456789:.3g} {0.000012345:.3g}")
# 0.333 1.23e+08 1.23e-05
Specifier Meaning Example result
.2f Fixed point, 2 decimals 1234.50
,.2f Thousands separator 1,234.50
_ Underscore separator 1_234_567
.1% Percentage, multiplied by 100 45.7%
05d Integer padded with zeros 00042
+d Always show the sign +5
x, o, b Hex, octal, binary ff, 377, 11111111
.3g Significant figures, switches to scientific when needed 1.23e+08

The comma separator always uses commas in groups of three. For Indian-style grouping, such as 12,34,567, or for locale-specific currency, use the locale module or a library such as Babel rather than f-strings alone.

Alignment and padding

print(f"{price:>12.2f}|{price:<12.2f}|{price:^12.2f}|")
#      1234.50|1234.50     |   1234.50   |

print(f"[{name:*^10}]")
# [***Asha***]

width = 8
print(f"[{price:{width}.1f}]")
# [  1234.5]

> aligns right, < aligns left and ^ centres. A character before the arrow, like *, sets the fill. The last example shows a nested field: the width itself comes from a variable, which is handy when building simple text tables whose column sizes depend on the data.

Numbers align right by default and strings align left, which is usually what you want in reports.

Dates and times

Datetime objects accept the same codes as strftime directly after the colon:

import datetime
d = datetime.datetime(2026, 11, 8, 14, 5)
print(f"{d:%d %b %Y, %H:%M} | {d:%A}")
# 08 Nov 2026, 14:05 | Sunday

Common codes include %Y for the four-digit year, %m for the month number, %d for the day, %H:%M for 24-hour time and %A for the weekday name. For machine-readable output, such as logs and APIs, prefer d.isoformat(), which produces a standard format other systems can parse.

The = debug shortcut

Add = after an expression, and Python prints the expression text as well as its value:

print(f"{name=} {price*qty=}")
# name='Asha' price*qty=3703.5

This arrived in Python 3.8 and is a big time-saver when you are tracing a bug. You can still add a format specifier after it, as in f"{price=:.2f}". Notice that the string value is shown with quotes. The = form uses repr() by default, which makes stray spaces and empty strings easy to spot.

You can choose the conversion yourself with !r for repr() and !s for str():

print(f"{name!r} {name!s}")
# 'Asha' Asha

For anything beyond a quick check, use the logging module, which our exception handling guide also recommends for recording errors.

Rounding surprises

This one confuses many people:

import decimal
print(f"{2.675:.2f} vs {decimal.Decimal('2.675'):.2f}")
# 2.67 vs 2.68

The float did not round up. That is not an f-string bug. The number 2.675 cannot be stored exactly in binary floating point, so the value Python holds is very slightly below 2.675, and it rounds down. The Decimal version holds the exact value and rounds as you would expect on paper.

Tip: For money, store and calculate amounts with decimal.Decimal or as whole numbers of the smallest unit, such as paise or cents. Use f-strings only for the final display.

Quotes, braces and backslashes

To show a literal brace, double it:

print(f"{{literal braces}} {qty}")
# {literal braces} 3

Before Python 3.12, a backslash was not allowed inside the braces, so code like f"{'\n'.join(lines)}" was a syntax error and people assigned the joined text to a variable first. Python 3.12 relaxed these rules, and our example ran fine on 3.13. If your code must support older versions, keep backslashes and repeated quote types out of the braces.

Also remember that the f prefix is what makes the magic happen. A plain string with braces is just text:

user = "x"
template = "Hello {user}"
print(template)
# Hello {user}

f-strings vs format() vs %

We timed one million runs of the same short message with each style using timeit:

f-string   0.129 s
format()   0.241 s
percent    0.135 s

On this machine the f-string was fastest, with the old % style close behind and str.format() slowest. The differences are tiny per call, so choose for readability first.

Style Example Best for
f-string f"{n} has {q}" Almost all new code
str.format() "{} has {}".format(n, q) Templates defined before the values exist
% formatting "%s has %s" % (n, q) Logging calls and older code
string.Template Template("$n has $q") Simple templates written by users

One place where % style still wins is logging. Writing logger.debug("user %s", name) lets the logging module skip building the message entirely when debug output is switched off, whereas an f-string is always evaluated.

When not to use f-strings

  • SQL queries. Never insert values into SQL with an f-string. It opens the door to SQL injection. Use parameters, such as cursor.execute("SELECT * FROM users WHERE name = ?", (name,)). Our SQL tutorial shows the safe pattern.
  • Shell commands. Build argument lists for subprocess instead of formatting a command string.
  • User-supplied templates. f-strings are evaluated in your code, so they cannot be loaded from a file or database. Formatting user-written templates with str.format() can also expose object attributes, so use string.Template or a proper template engine.
  • Translations. Text that needs translating usually goes through a function such as gettext first, with placeholders filled afterwards.

Common mistakes

  • Forgetting the f. The braces appear literally in the output.
  • Using :.2f on a string. You get ValueError: Unknown format code 'f'. Convert with float() first.
  • Putting heavy logic in the braces. If an expression needs explaining, compute it on the line before.
  • Expecting .2f to fix float precision. It changes only how the number is displayed.

Putting it together: a small text report

Alignment, separators and decimals combine nicely for console reports and log summaries:

rows = [("Pen", 3, 10.0), ("Notebook", 12, 45.5), ("Desk lamp", 1, 1299.0)]
print(f"{'Item':<12}{'Qty':>5}{'Price':>10}")
for name, qty, price in rows:
    print(f"{name:<12}{qty:>5}{price:>10,.2f}")
total = sum(q * p for _, q, p in rows)
print(f"{'Total':<12}{'':>5}{total:>10,.2f}")

# Item          Qty     Price
# Pen             3     10.00
# Notebook       12     45.50
# Desk lamp       1  1,299.00
# Total              1,875.00

The column headers are plain strings inside the braces, formatted with the same widths as the data, so everything lines up. Triple-quoted f-strings work too, and an inline conditional keeps grammar correct:

user, n = "Asha", 3
msg = f"""Hi {user},
You have {n} new {'message' if n == 1 else 'messages'}."""
# Hi Asha,
# You have 3 new messages.

For anything wider or more complex, such as HTML emails or documents, move to a template engine like Jinja, which keeps layout and data apart.

Final thoughts

f-strings make formatted output readable at a glance. Learn a handful of specifiers, .2f, ,, %, alignment arrows and date codes, plus the = debug shortcut, and you will cover nearly every everyday need. Keep them for display text, and use parameters for SQL and proper templates for anything users can edit.

Frequently asked questions

What is an f-string in Python?

It is a string literal prefixed with f, where expressions inside curly braces are evaluated and inserted as text. f-strings were added in Python 3.6.

How do I format a float to 2 decimal places with an f-string?

Use the .2f specifier, as in f”{price:.2f}”. Add a comma, as in f”{price:,.2f}”, to include a thousands separator.

What does = do inside an f-string?

It prints the expression and its value together, such as name=’Asha’. It was added in Python 3.8 and is useful for quick debugging.

Are f-strings faster than format()?

Usually, yes. In our timing of one million calls, f-strings took 0.129 seconds against 0.241 seconds for str.format(). Choose for readability first, since both are fast.

Can I use f-strings for SQL queries?

No. Formatting values into SQL text allows SQL injection. Pass values as query parameters instead.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →