python_string_formatting

Python String formatting

In both Python 3.X and 2.X (as of 3.0 and 2.6), normal str strings support two different flavors of string formatting — operations that format objects according to format description strings:

The original expression (all Python versions), coded with the % operator: fmt % (values)

The newer method (3.0, 2.6, and later), coded with call syntax: fmt.format(values)

Both produce new strings based on possibly type-specific substitution codes. Their results may be displayed, or assigned to variables for later use:

'%s, %s, %.2f' % (42, 'spam', 1 / 3.0) '42, spam, 0.33' »> '{0}, {1}, {2:.2f}'.format(42, 'spam', 1 / 3.0) '42, spam, 0.33'

Although the method call seems to have evolved more rapidly in recent years, the expression is used extensively in existing code, and both forms are still fully supported. Moreover, although some view the method form as marginally more mnemonic and consistent, the expression is often simpler and more concise. As these two forms are largely just minor variations on a theme of equivalent functionality and complexity, there is today no compelling reason to recommend one over the other.

python_string_formatting.txt · Last modified: 2024/04/28 03:21 (external edit)