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
