liveBook · Manning

Format operator

As explained in The Quick Python Book, Fourth Edition

The format operator is Python's percent operator when applied to a format string and values to produce formatted text.

The format operator is Python’s percent operator when its left operand is a format string. It scans formatting sequences such as %s and substitutes values from the right operand, producing new text. section 6.8 section 6.8.1

Core rules:

  • Use a tuple for positional substitutions: each value fills the corresponding formatting sequence from left to right. section 6.8
  • %s converts its value with str automatically, so the supplied value need not already be a string. section 6.8
  • Add width, precision, and alignment options to control output; for example, %-6.2f creates a six-character, left-justified field with two decimal places. section 6.8.1
  • Use named sequences such as %(pi).2f with a dictionary when templates contain many substitutions or reuse values. section 6.8.2

Positional and named formatting

"%s is the %s of %s" % ("Ambrosia", "food", "the gods") # 'Ambrosia is the food of the gods' num_dict = {'e': 2.718, 'PI': 3.14159} print("%(PI).2f - %(PI).4f - %(e).2f" % num_dict) # 3.14 - 3.1416 - 2.72 section 6.8 section 6.8.2

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

Try a width, precision, and alignment specification interactively to see how padding changes the result. section 6.8.1

This is the old style of string formatting: useful when reading earlier or ported Python code, but not recommended for new code because it is slated for deprecation and removal. section 6.8 section 3.2.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains positional and named substitution, conversion, width, precision, alignment, and deprecation, without implementation internals.
Examples
Demonstrates prose substitution, list conversion, floating-point precision, alignment, and dictionary-based reuse.
What it assumes
Assumes general Python and string knowledge while deferring detailed dictionaries to a later treatment.
What you can do after
Apply it via Python’s percent operator to produce positional, named, and numerically controlled formatted strings.
How it connects
Connects string formatting with tuples, dictionaries, print, string conversion, f-strings, and C’s sprintf.

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.