String formatting means building a string that includes values from your program, such as a name, a price, or today’s date. Python offers several ways to do it, but f-strings (formatted string literals, added in Python 3.6) are the fastest, the most readable, and the one you should use by default.
In this tutorial, you’ll learn how f-strings work, how to format numbers, dates, and text with the format specification mini-language, how to debug with f-strings, and when the older str.format(), % operator, and Template strings are still useful.
Key terms used in this article:
- f-string: A string literal prefixed with
forFthat can contain expressions inside curly braces, such asf"Hello, {name}". - Replacement field: The
{...}part of an f-string. Python replaces it with the value of the expression inside. - Format specifier: Instructions after a colon inside the braces that control how a value looks, such as
{price:.2f}. - Interpolation: Inserting values into a string.
Table of contents
- Why string formatting matters
- f-string basics
- Formatting numbers
- Aligning text and building tables
- The format specification mini-language
- Formatting dates and times
- Debugging with the = specifier
- Conversion flags: !s, !r, and !a
- Formatting your own objects
- The str.format() method
- The % operator (old style)
- Template strings
- Template string literals (t-strings) in Python 3.14
- Which formatting method should you use?
- Common mistakes
- Practice exercises
- Summary
Why string formatting matters
Without formatting, you’d have to join strings with + and convert every number with str():
Output:
My name is Jessa and I am 28 years old. My name is Jessa and I am 28 years old.
The f-string version is shorter, easier to read, and converts values to text automatically.
f-string basics
Put the letter f (or F) before the opening quote, and write any variable or expression inside curly braces {}:
Output:
It is 21.5 degrees in Paris. Uppercase F works too: Paris
f-strings work with single quotes, double quotes, and triple quotes.
Expressions inside f-strings
The braces can hold any valid Python expression: arithmetic, function calls, method calls, indexing, and even conditional expressions.
Output:
7 + 3 = 10 Number of items: 3 First item in uppercase: PEN User: Kelly (admin) 7 is odd
Keep the expressions short. If the logic gets complicated, calculate the value in a variable first, then insert the variable.
Multi-line f-strings
Use triple quotes for a multi-line f-string, or put several f-strings inside parentheses. Python joins adjacent string literals automatically:
Output:
Customer: Emma Total: $149.5 Customer Emma spent $149.5 today.
Quotes and backslashes
Use a different quote type inside the braces than the one that surrounds the f-string, for example single quotes inside a double-quoted f-string. Since Python 3.12, you can reuse the same quote type and use backslashes inside the expression part, but different quotes keep your code compatible with older versions.
Output:
Language: Python Words: one two three
Printing literal braces
To show a curly brace in the output, double it: {{ prints { and }} prints }.
Output:
{value} is replaced by 42
Set literal: {42}
Formatting numbers
Add a colon after the expression, followed by a format specifier. The specifier controls decimals, width, separators, signs, and number systems.
Decimal places
.Nf rounds a number to N digits after the decimal point:
Output:
3.14 3.1416 $49.50 10.0
Thousands separators
Use , or _ to group digits in thousands:
Output:
8,100,000,000 8_100_000_000 1,234,567.89
Percentages
% multiplies the number by 100 and adds a percent sign:
Output:
85.670000% 85.7% Completion: 85%
Scientific notation and general format
Output:
1.496000e+11 1.50e+11 1.234e-05 1.2345e-05
Sign, padding with zeros, and width
Output:
+42 -42 42 00042 007 0003.500
Binary, octal, and hexadecimal
Output:
11111111 377 ff FF 0xff 0b11111111 00000101
Aligning text and building tables
Set a width and an alignment character to line up text in columns:
| Specifier | Meaning |
|---|---|
< | Left-align (default for strings) |
> | Right-align (default for numbers) |
^ | Center |
= | Put padding after the sign, as in -0042 |
You can also put a fill character before the alignment symbol:
Output:
|Python | | Python| | Python | |***Python***| |Python------|
Combining width and precision makes neat tables:
Output:
Item Qty Price ------------------------- Keyboard 3 49.99 Mouse 12 19.50 Monitor 1 229.00
Dynamic width and precision
You can put another replacement field inside the format specifier to set the width or precision at runtime:
Output:
| 3.142| 3.1 3.14 3.142
The format specification mini-language
Every format specifier follows the same pattern. Each part is optional, but the order is fixed:
[[fill]align][sign][z][#][0][width][grouping][.precision][type]
| Part | Examples | What it does |
|---|---|---|
| fill | *, -, 0 | Character used for padding |
| align | <, >, ^, = | Alignment within the width |
| sign | +, -, space | How to show the sign |
| z | z | Turns -0.0 into 0.0 after rounding (3.11+) |
| # | # | Adds 0b, 0o, 0x prefixes |
| 0 | 0 | Zero-pads numbers |
| width | 10 | Minimum total width |
| grouping | ,, _ | Thousands separator |
| precision | .2 | Digits after the decimal point, or maximum length for strings |
| type | f, e, g, %, d, b, o, x, X, s | Presentation type |
Precision also truncates strings:
Output:
Structural Structural...
Formatting dates and times
datetime objects accept strftime() codes directly inside an f-string:
Output:
2026-12-04 04/12/2026 14:30 Friday, December 04, 2026 02:30 PM
| Code | Meaning | Example |
|---|---|---|
%Y | 4-digit year | 2026 |
%m | Month as number | 12 |
%d | Day of month | 04 |
%B / %b | Month name, full / short | December / Dec |
%A / %a | Weekday, full / short | Friday / Fri |
%H / %I | Hour, 24-hour / 12-hour | 14 / 02 |
%M, %S | Minutes, seconds | 30, 05 |
%p | AM or PM | PM |
Debugging with the = specifier
Add = after an expression (Python 3.8+) to print both the expression and its value. It’s perfect for quick debugging:
Output:
x=10 x * y=30 name='Jessa' x / y=3.33 x = 10
Conversion flags: !s, !r, and !a
By default, f-strings use str() to convert a value. Conversion flags let you choose:
| Flag | Calls | Use it for |
|---|---|---|
!s | str() | Readable output (the default) |
!r | repr() | Unambiguous output, such as strings with quotes |
!a | ascii() | Escaping non-ASCII characters |
Output:
café 'café' 'caf\xe9'
!r is useful for spotting hidden spaces or empty strings in your data: f"{value!r}" shows ' ' instead of blank output.
Formatting your own objects
f-strings call an object’s __format__() method, which receives the format specifier. You can implement it in your own classes:
Output:
Today: 21.5°C Today: 70.7°F
The str.format() method
Before f-strings, str.format() was the main way to format strings. It uses the same format specifiers, but the values are passed as arguments:
Output:
Hello, Jessa! You are 28 years old. A vs B, then B vs A Kelly scored 91.3 Emma lives in Rome
str.format() is still the right tool when the template is created before the values exist, for example when templates are stored in a file, a database, or a settings dictionary:
Output:
Welcome, Jessa! You have 5 new messages.
The % operator (old style)
The % operator is the oldest formatting style. You’ll still see it in older code and in the logging module:
Output:
Hello, Jessa! Jessa has $1520.76 Jessa | 1520.8| Kelly has 3 items
| Placeholder | Type |
|---|---|
%s | String (any object, via str()) |
%d | Integer |
%f | Float (%.2f for 2 decimals) |
%x | Hexadecimal |
%% | A literal percent sign |
Template strings
string.Template uses $name placeholders and can’t run expressions, which makes it safer when the template comes from users:
Output:
Hi Jessa, your order #1042 has shipped. Hi Kelly, your order #$order_id has shipped.
Never call .format() on a string supplied by a user. A malicious template can read attributes of the objects you pass in. Use Template for user-supplied templates.
Template string literals (t-strings) in Python 3.14
Python 3.14 adds t-strings, written with a t prefix. They look like f-strings, but instead of producing a str, they produce a Template object that keeps the static text and the interpolated values separate. Libraries can then process the values safely, for example by escaping HTML or SQL:
For everyday string building, keep using f-strings. t-strings are meant for libraries that need to inspect or sanitize values.
Which formatting method should you use?
| Method | Example | When to use |
|---|---|---|
| f-string | f"{name} is {age}" | Default choice for almost all code |
str.format() | "{} is {}".format(name, age) | Templates defined before the values exist |
% operator | "%s is %d" % (name, age) | Legacy code and logging calls |
Template | Template("$name").substitute(...) | Templates provided by users |
f-strings are also the fastest, because Python compiles them into efficient bytecode instead of parsing a template at runtime.
Common mistakes
- Forgetting the f prefix.
"Hello, {name}"prints the braces literally. - Using the wrong format type.
f"{'abc':.2f}"raisesValueError: Unknown format code 'f' for object of type 'str'. Convert text to a number first withfloat(). - Using f-strings in logging calls. Write
logging.info("User %s logged in", user)so the message is only built when it’s actually logged. - Expecting rounding to always go up.
f"{2.675:.2f}"gives2.67, because2.675can’t be stored exactly as a float. Use thedecimalmodule for money.
Output:
Hello, {name}
Hello, Jessa
2.67
Practice exercises
Exercise 1: Print a price list where item names are left-aligned in 12 characters and prices are right-aligned with 2 decimals in 8 characters.
Output:
Coffee 3.50 Sandwich 7.25 Cake 4.00
Exercise 2: Show a progress message such as Downloaded 45 of 120 files (37.5%).
Output:
Downloaded 45 of 120 files (37.5%)
Exercise 3: Print the numbers 0 to 5 as 4-digit binary, padded with zeros.
Output:
0 -> 0000 1 -> 0001 2 -> 0010 3 -> 0011 4 -> 0100 5 -> 0101
Summary
- Prefix a string with
fand put expressions in{}to build strings quickly and readably. - Add a format specifier after a colon:
.2ffor decimals,,for thousands,%for percentages,>10for alignment,05for zero padding, andb/xfor binary and hex. - Format dates with
strftimecodes such as{now:%Y-%m-%d}. - Use
{expr=}to debug and!rto see the exact representation of a value. - Use
str.format()for templates defined in advance,%only in legacy code and logging, andTemplatefor user-supplied templates.
Also, See:

Leave a Reply