liveBook · Manning

Format string

As explained in Python How-To

A format specifier is the portion of a formatting expression that controls how a value is represented, such as its precision or alignment.

A format specifier controls how an interpolated value appears in an f-string. It follows a colon inside the braces, such as f"{value:^10}" for centered, width-limited output. section 2.1.4

Use common specifiers to shape readable text and numeric output:

  • <, >, and ^ select left, right, and center alignment; an optional character supplies padding. section 2.1.4
  • :,d, :b, :o, and :x represent integers in decimal, binary, octal, and hexadecimal forms. section 2.1.4
  • .2f limits a float to two decimal places, while :e and :% select scientific and percentage notation. section 2.1.4

Align task records

task_ids = [1, 2, 3] task_names = ['Do homework', 'Laundry', 'Pay bills'] task_urgencies = [5, 3, 4] for i in range(3): print(f'{task_ids[i]:^12}{task_names[i]:^12}{task_urgencies[i]:^12}') # 1 Do homework 5 # 2 Laundry 3 # 3 Pay bills 4 A reusable function can accept a format string such as '^15' or '^18', avoiding repeated formatting code. section 2.1.4

Format temperature input

temperature = float(input()) if temperature < 10: message = "It's cold!" elif temperature <= 25: message = "It's cool!" else: message = "It's hot!" print(f"You entered {temperature:.1f} degrees. {message}") A value such as 15.75 is displayed as 15.8. section 2.2.5

Listing 2.2 Applying format specifiers in f-strings
task_ids = [1, 2, 3]
task_names = ['Do homework', 'Laundry', 'Pay bills']
task_urgencies = [5, 3, 4]
 
for i in range(3):
    print(f'{task_ids[i]:^12}{task_names[i]:^12}{task_urgencies[i]:^12}') #1
 
# Output the following lines:
     1      Do homework      5      
     2        Laundry        3      
     3       Pay bills       4

Shows aligned identifiers, names, and urgency values in a complete f-string listing with representative output. section 2.1.4

How Python How-To covers it

How deep it goes
Defines alignment, padding, width, precision, and numeric notation with worked examples, but does not descend into formatting internals.
Examples
Uses aligned task records, reusable format widths, formatted temperatures, percentages, scientific notation, and base conversions.
What it assumes
Assumes basic f-strings and conditional logic, while emphasizing float conversion before comparisons in the temperature task.
What you can do after
Apply it via Python f-strings to align text, control precision, and represent integers and floats in useful notations.
How it connects
Connects f-strings with string alignment, numeric representation, float conversion, and the DRY principle.

Also explained in

Compare how 5 books explain format 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.