Home »
Python
Python String Formatting: % vs. .format() Method
By IncludeHelp Last updated : December 15, 2024
Old Style vs. New Style Formatting
Often the string formatters in Python are referred to as old style and new style. The old-style is '%' and .format is known as the new style.
Simple Positional Formatting
Simple positional formatting is the most common use-case. This formatting is used if the order of the arguments is not likely to change and there are very few elements to be concatenated.
Example
# string concatenation using %
print('%s %s'%('one','two'))
# string concatenation using .format
print('{} {}'.format('one','two'))
Output
one two
one two
Explicit Positional Index
With the new style formatting, it is possible to give placeholders an explicit positional index. This allows for rearranging the order of display without changing the arguments. This feature is not available in the old style.
Example
print('{0} {1}'.format('one','two'))
print('{1} {0}'.format('one','two'))
Output
one two
two one
Padding and Aligning Strings
By default, values are formatted to take up only as many characters as needed to represent the content. It is, however, possible to define that a value should be padded to a specific length.
Example
print('%10s'%('test'))
print('{:>10}'.format('test'))
Output
test
test
Truncating Long Strings
It is also possible to truncate overly long values to a specific number of characters. The number behind a . (dot) in the format specifies the precision of the output. For strings that means that the output is truncated to the specified length. In our example, this would be 3 characters.
Example
print('%.3s'%('includehelp',))
print('{:.3}'.format('includehelp'))
Output
inc
inc
Formatting Numbers
String formatting also supports numbers.
Example
print('%d' %(10000))
print('{:d}' .format(10000))
Output
10000
10000
Parametrized Formats
New style formatting allows all of the components of the format to be specified dynamically using parametrization. Parametrized formats are nested expressions in braces that can appear anywhere in the parent format after the colon. Old style formatting also supports some parametrization but is much more limited. Namely, it only allows parametrization of the width and precision of the output.
Example
from datetime import datetime
dt = datetime(2019, 12, 19, 4, 5)
print('{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M'))
Output
2019-12-19 04:05
Custom Objects
The datetime example works through the use of the __format__() magic method. However, one defines custom format handling in own objects by overriding this method. This gives complete control over the format syntax used.
Example
class Type2000(object):
def __format__(self, format):
if (format == 'test-format'):
return "This is format example for include help."
return 'Type 2000'
print('{:test-format}'.format(Type2000()))
Output
This is format example for include help.