liveBook · Manning

Formatting sequence

As explained in The Quick Python Book, Fourth Edition

A formatting sequence is a percent-prefixed pattern in a format string that specifies how a corresponding value is converted and inserted into the resulting text.

A formatting sequence is a percent-prefixed pattern inside a format string. It specifies what value replaces the pattern and how that replacement is formatted when the % operator produces a new string. section 6.8.1 section 6.8

Use formatting sequences to control both the source of a value and its visible representation:

  • %s inserts the corresponding value from a right-side tuple and automatically applies str to it. section 6.8
  • More elaborate sequences can specify field width, decimal precision, and alignment; in %-6.2f, 6 is the width, 2 is the precision, and - left-justifies the number. section 6.8.1
  • Named sequences place a key in parentheses after %, take a dictionary on the right, and can reuse values without positional bookkeeping. section 6.8.2

Formatting a number

"Pi is <%-6.2f>" % 3.14159 produces 'Pi is <3.14 >': the number has two decimal places, occupies six characters, and is left-aligned.

Using named values

num_dict = {'e': 2.718, 'PI': 3.14159}; "%(PI).2f - %(PI).4f - %(e).2f" % num_dict produces '3.14 - 3.1416 - 2.72'.

"Pi is <%-6.2f>" % 3.14159 # use of the formatting sequence: %–6.2f
 
'Pi is <3.14  >'

Inspect the runnable width, precision, and alignment example alongside its visible padding. section 6.8.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains substitution, tuples, dictionaries, width, precision, alignment, and reuse, but defers the complete option set to documentation.
Examples
Demonstrates text substitution, list conversion, numeric width and precision, and repeated named values.
What it assumes
Assumes tuple-based substitution and introduces named substitution alongside dictionaries whose details are deferred.
What you can do after
Apply it via the percent operator to construct formatted strings from positional tuples or named dictionaries.
How it connects
Connects string formatting with the percent operator, tuples, dictionaries, string conversion, and numeric precision.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.