liveBook · Manning

F-string

As explained in Python How-To

An f-string is a string literal syntax that evaluates embedded expressions and formats their values within the string.

Need to turn a task’s name and urgency into a readable line? An f-string places values directly in a string literal. Prefix the quoted string with `f`, then put each variable inside curly braces. Integers and other nonstring values are converted for output. section 2.1 section 2.1.2

Build a task label

```python name = "Homework" urgency = 5 label = f"Name: {name}; Urgency Level: {urgency}" print(label) # Name: Homework; Urgency Level: 5 ``` The braces mark the values to insert; the punctuation outside them stays as written. section 2.1 section 2.1.2

Braces can also contain an expression, such as `tasks[0]`, `task_name.title()`, or `number * number`. The expression is evaluated before its result appears in the string. Keep it short: if calculating a value inside the braces takes effort to read, give that value a descriptive variable first. section 2.1.3

Format values for display

```python name = "Laundry" urgency = 3 price = 130.675 print(f"{name:^12} {urgency:^12}") print(f"Price: {price:.2f}") # Laundry 3 # Price: 130.68 ``` A colon inside the braces starts an optional format specifier. Here `^12` centers a value in a field 12 characters wide, while `.2f` displays a number with two decimal places. section 2.1.4

Choose a specifier for the output you need:

  • `<`, `>`, and `^` align text left, right, and center; a field can use spaces or a chosen padding character. section 2.1.4
  • `,d` separates digits in a large integer; `.2f` sets two decimal places; `.2%` displays a percentage with two decimal places. section 2.1.4
  • If several fields need the same specifier, store it once and use a nested field such as `f'{name:{fmt}}'` rather than repeating it. section 2.1.4

Print literal curly braces

To show braces around a formatted price, double the braces that should print literally: ```python product = {"name": "Vacuum", "price": 130.675} print(f"{product['name']}: {{{product['price']:.2f}}}") # Vacuum: {130.68} ``` section 2.1.6

Prefer f-strings when assembling readable output from related values. For a few plain strings, concatenation is also reasonable; when the strings are already in an iterable, consider `join` instead. section 2.1.5 section 2.3.4

Table 2.2 Common format specifiers for formatting numbers with f-strings (view table figure)

Numeric type

F-string

Output

Description

int

f"{number:b}"

"1111"

Binary format, using base 2

 

f"{number:c}"

"\x0f"

Unicode representation of the integer

 

f"{number:d}"

"15"

Decimal format, using base 10

 

f"{number:o}"

"17"

Octal format, using base 8

 

f"{number:x}"

"f"

Hexadecimal format, using base 16

float

f"{point:.2e}"

"1.23e+00"

Scientific notation

 

f"{point:.2f}"

"1.23"

Fixed-point notation with two-digit precision

 

f"{point:.2g}"

"1.23"

General format, automatically applying e or f

 

f"{point:.2%}"

"123.45%"

Percentage with two-digit precision2

Compare common integer and floating-point format specifiers when choosing a numeric display. section 2.1.4

How Python How-To covers it

How deep it goes
Works through interpolation, expressions, alignment, numeric specifiers, and escaping braces, while cautioning against complicated embedded expressions.
Examples
Uses task labels, aligned task records, formatted numbers, and a price tag requiring literal curly braces.
What it assumes
Assumes familiarity with Python variables and strings while explaining interpolation and the distinction between expressions and statements.
What you can do after
Build it from scratch: produce readable Python output with embedded values, appropriate format specifiers, and literal braces when needed.
How it connects
Connects string interpolation to expressions, text alignment, numeric formatting, string concatenation, and `join`.

Also explained in

Compare how 4 books explain f-string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.