Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 149 ยท Data Types

String Formatting

Format text with Python f-strings - expressions, the = specifier, alignment, padding, decimals, thousands separators, percentages, dates and str.format().

Programs constantly turn values into text: a total on a receipt, a row in a report, a log message, a date in a file name. String formatting is how you control exactly what that text looks like: how many decimals, how wide a column, whether there are thousands separators.

Modern Python does nearly all of this with f-strings. You met them briefly in Input and Output. This lesson goes in depth: embedding expressions, the debugging = shortcut, the format specification mini-language for alignment and numbers, dates, and the older str.format() method you'll still see in existing code.

f-string basics

An f-string is a string literal with an f (or F) before the opening quote. Anything inside curly braces {} is a Python expression: it's evaluated, converted to text, and inserted in place.

Python Expressions inside braces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Any expression works: arithmetic, function and method calls, indexing, even conditional expressions. Keep them short, though. If an expression gets complicated, compute it in a variable first and put just the name in the braces.

To print a literal brace, double it: f"{{not replaced}}" gives {not replaced}.

Note: Since Python 3.12, f-strings can reuse the same quote character inside the braces (f"{data["key"]}") and expressions may span several lines. Older versions needed the other quote type inside, as in f"{data['key']}", which still works everywhere.

The = specifier for debugging

Add = after an expression and the f-string prints the expression's text too. It's a fast way to inspect values while debugging:

Python Self-documenting expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output looks like width=12, so you don't have to type every label twice.

Conversions: !r, !s and !a

By default, values are converted with str(). Add !r to use repr() instead, which shows strings with quotes and makes hidden whitespace visible:

Python
command = "  stop\n"
print(f"Got {command}!")     # the newline breaks the line
print(f"Got {command!r}!")   # Got '  stop\n'!

!s forces str() (the default), and !a is like !r but escapes non-ASCII characters. Note that = uses repr() automatically unless you add a format spec.

The format specification

After the expression, a colon starts the format spec, a compact code that controls the layout:

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

Every part is optional. The next sections cover each one, but here's a preview: {price:>10,.2f} means "right-aligned, 10 characters wide, with thousands separators, 2 decimals, as a fixed-point number".

Width and alignment

A number after the colon sets the minimum width. Alignment symbols choose where the value sits inside that width: < left, > right, ^ centered. Text is left-aligned by default and numbers right-aligned. Put a fill character before the alignment symbol to pad with something other than spaces:

Python Alignment and fill

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The width is a minimum: longer values are never cut off, they just push the layout. To truncate text, use a precision, as in f"{word:.2}" which gives te.

Numbers: precision and type

The type letter says how to present a number, and the precision (after a dot) says how many digits:

Python Number presentation types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Type Meaning f"{1234.5:โ€ฆ}"
f fixed-point decimals .2f โ†’ 1234.50
e scientific notation .2e โ†’ 1.23e+03
g general: fixed or scientific, whichever fits .3g โ†’ 1.23e+03
% percentage .0% on 0.25 โ†’ 25%
d integer (decimal) d on 42 โ†’ 42
b o x X binary, octal, hex x on 255 โ†’ ff

Formatting rounds the displayed value but never changes the variable itself.

Thousands separators and signs

A comma or underscore in the spec groups digits in threes. A sign option controls plus signs: + shows a sign on every number, and a space reserves room for one so positive and negative numbers line up:

Python Grouping and signs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The comma style always uses , and .. For number formats that follow a country's conventions (such as 1.234,56 in Germany), use the locale module or a library such as Babel.

Nested fields

The width or precision can come from a variable: put another pair of braces inside the spec:

Python
width = 12
decimals = 3
print(f"[{3.14159:>{width}.{decimals}f}]")   # [       3.142]

That's useful when the column width depends on the data, as in the next example.

Putting it together: a table

Alignment, width and number formats combine to produce clean, readable tables:

Python A formatted report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

name_width is computed from the longest product name, so the table adapts to its data. grand_total += line_total is shorthand for grand_total = grand_total + line_total.

Formatting dates and times

datetime objects understand their own format codes inside an f-string. Codes start with %: %Y is the four-digit year, %m the month number, %d the day, %H:%M the hour and minute, %A the weekday name and %B the month name:

Python Dates in f-strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

%Y-%m-%d (the ISO 8601 format) is the safest choice for data and file names, because it sorts correctly and isn't ambiguous across countries. The Dates and Times lesson covers parsing, time zones and arithmetic.

str.format()

Before f-strings arrived in Python 3.6, the standard way was the str.format() method. It uses the same braces and the same format spec, but the values are passed as arguments:

Python str.format()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

f-strings are shorter and easier to read, so prefer them in new code. str.format() is still the right tool when the template is defined separately from the values, for example a message stored in a settings file, because an f-string is evaluated immediately where it's written.

The old % operator

Very old code formats with %, borrowed from the C language: "%s is %d years old" % ("Kai", 29). It still works, and Python's logging module uses this style internally, but avoid it in new code.

Template strings (t-strings)

Python 3.14 added t-strings, written with a t prefix: t"Hello {name}". They look like f-strings but don't produce a str. Instead, they produce a Template object that keeps the text and the values separate, so a library can process the values before combining them, for example escaping them for HTML or SQL. They're a tool for library authors; for everyday text, f-strings remain the answer.

Never build SQL queries or HTML with f-strings from user input. Inserting untrusted text directly can let attackers inject their own code. Use your database library's parameters (such as ? placeholders) or a template engine that escapes values.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does f"{3.14159:.2f}" produce?

    .2f means fixed-point notation with 2 digits after the decimal point, rounded.
  2. 2. With x = 5, what does f"{x=}" produce?

    The = specifier prints the expression's text, an equals sign, and the value. It's a handy debugging shortcut.
  3. 3. Which spec right-aligns a value in a field 8 characters wide?

    > aligns right, < aligns left and ^ centers.
  4. 4. What does f"{1234567:,}" produce?

    The comma option groups digits in threes using commas. Use the locale module or a library for other national conventions.
  5. 5. When is str.format() a better choice than an f-string?

    An f-string is evaluated immediately where it's written. str.format() can fill a template that was defined elsewhere, such as in a settings file.

Summary

  • f-strings (f"...{expr}...") insert the value of any expression; double the braces for a literal {.
  • {expr=} prints the expression and its value, perfect for debugging. !r shows the repr().
  • The format spec after : controls fill, alignment (<, >, ^), sign, width, grouping (, or _), precision and type.
  • Number types: f fixed, e scientific, g general, % percentage, b/o/x other bases.
  • Widths and precisions can come from variables with nested braces: {x:>{width}}.
  • Dates use % codes inside the spec: f"{day:%Y-%m-%d}".
  • str.format() uses the same specs and suits templates defined elsewhere; avoid % formatting in new code.
  • Python 3.14's t-strings create Template objects for libraries that need to process values safely.

Next: Booleans and Truthiness, where you'll learn how Python decides what counts as true or false.