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
