Introduction
Python 2.6 introduced the string.format() method with a slightly different syntax from the existing %
operator.
Background
Older '%' string formatter.
Prior to python 2.6, a simpler string
formatter '%
' was available.
It was easy to use but the number of arguments that it could accept were limited.
For example:
>>> ex = (1,2,3)
>>> print "hi there %s" %ex #this would throw a TypeError
To make it work:
>>> print "hi there %s" % (ex,) #looks ugly, though!
.format()
doesn't have such issues.
Something that the modulo operator ( %
) can't do:
>>> ex = (12,45,22222,103,6)
>>> print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*ex)
>>> 12 22222 45 22222 103 22222 6 22222
Moreover, for a long list of arguments, it is easy that a variable could be missed.
>>> print "%s, %s, %s, %s, %s, %s, %s, %s" % (a,b,c,d,e,f,g,h)
Using the Format Method
Accessing Arguments by Position
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # 2.7+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
'abracadabra'
Accessing Arguments by Name
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
Passing a Dictionary
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
Passing a List
>>> coord = ['37.24N', '-115.81W']
>>> 'Coordinates: {}, {}'.format(*coord) #can be also 'Coordinates: {0}, {1}'.format(*coord)
>>> 'Coordinates: 37.24N, -115.81W'
Converting Values to Different Bases
You can use the following letters to convert a number to their bases - decimal, hex, octal, binary.
>>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
Use Format as a Function
You can use .format
as a function which allows for some separation of text and formatting from code.
For example, at the beginning of your program, you could include all your formats and then use later.
# defining formats
>>> email_f = "Your email address is {email}".format
# use somewhere else
>>> print(email_f(email="bob@example.com"))
Named Arguments
The newer format
method can be used as a templating engine and use named arguments, instead of requiring a strict order.
>>> madlib = " I {verb} the {object} off the {place} ".format(object="cheese", verb="took", place="table")
>>> I took the cheese off the table
Escaping Braces
If you need to print braces when using format
, use braces twice!
>>> print(" The {} set is often represented as {{0}} ".format("empty"))
>>> The empty set is often represented as {0}
Aligning the Text and Specifying a Width
>>> print '{:<30}'.format('left aligned')
>>> 'left aligned '
>>> print '{:>30}'.format('right aligned')
>>> ' right aligned'
>>> print '{:^30}'.format('centered')
>>> ' centered '
>>> print '{:*^30}'.format('centered') # use '*' as a fill char
>>> '***********centered***********'
Using the comma(,) as a Thousands Separator
Introduced in Python 3.1 - PEP
>>> print '{:,}'.format(1234567890) #backported to version 2.7
>>> '1,234,567,890'
Expressing a Percentage
>>> points = 19.5
>>> total = 22
>>> print 'Correct answers: {:.2%}'.format(points/total)
>>> 'Correct answers: 88.64%'
Another Point
Since format
is a function, it can be used as an argument in other functions.
>>> li = [12,45,78,784,2,69,1254,4785,984]
>>> print map('the number is {}'.format, li)
>>> ['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the number is 984']
Points of Interest
format
is around 1x faster than using the %
operator. But for some cases the %
operator maybe faster too.
One issue with format
is the extra function call overhead, which consumes somewhere around 50-150ns.
Results using timeit
:
>>>timeit( "%d and %.1f" % (4,2.2) )
1000000 loops, best of 3: 633 ns per loop
>>>timeit( "{} and {:.1f}".format(4,2.2) )
1000000 loops, best of 3: 585 ns per loop