Format
code
Description
Example
%
A literal percentage sign.
‘%.2f%%’
% 32.1
#
‘32.10%’
c
Character, specified directly or using an ASCII code.
‘%c-%c’
% (0x61,
‘a’)
# ‘a-a’
d or i
Integer (decimal).
‘%d %d’
% (4, -7)
# ‘4 -7’
e or E
Exponential floating point. Lower case and upper case
respectively.
‘%.2e’ %
(7,)
#
‘7.00e+00’
‘%.2E’ %
(-1.3e-7)
# ‘-1.30E-
07’
f or F
Floating point.
‘%.3f’ %
(7)
# ‘7.000’
‘%6.2f’ %
(7.3999)
# ‘ 7.40’
g or G
General floating point, using an exponent above or at the
precision number (after the point) and also below 10
−4
.
Lower case and upper case respectively.
‘%.2g’ %
(100,)
# ‘1e+02’
‘%.3G’ %
(100,)
# ‘100’
o
Octal (base 8).
‘%o’ %
(100,)
# ‘144’
r
String, converting objects with repr().
‘%r %r’ %
(None,
‘abc’)
# ‘None
“abc”’
s
String, converting objects with str().
‘%s %s’ %
(True,
‘abc’)
# ‘True
abc’
x or X
Hexadecimal (base 16). Using lower-case a–f or upper-
case A–F respectively.
‘%x’ %
(1023,)
# ‘3ff’
Control
options
Description
Example
0
Pads numeric values with leading zeros.
‘%05i’ %
(7,)
# ‘00007’
-
Left justifies the string, so spaces occur to the right.
‘%-5s’ %
(‘abc’)
# ‘abc ‘
Places a space before a positive number.
‘% .2f’ %
(123)
# ‘ 123.00’
+
Puts a plus sign before a positive number.
‘%+.2f’ %
(123)
#
‘+123.00’
#
For certain formats, uses an alternative form.
‘%#x’ %
(1023,)
# ‘0x3ff’
New-style formatting
From Python 2.6 a new style of formatting was introduced with the .format() method for
strings. The general idea is that curly braces are placed inside the string and the method
inserts the stated values into the appropriate places, formatting appropriately. The braces
accept an identifier stating which of the values to place in which slot. For example, here
the values 6 and 7 are placed in slots ‘{0}’ and ‘{1}’ respectively, using the index of each
argument as an identifier:
'X:{0} Y:{1}'.format(6, 7) # Gives 'X:6 Y:7'
From Python version 2.7 the identifiers are optional and the order of inserted values is
the same as the order of arguments, so we could also do the following to get the same
result as before:
'X:{} Y:{}'.format(6, 7) # From Python 2.7
However, by using identifiers, the order in which the values are placed into the string
can be controlled, so, for example, we could reverse the order by swapping the identifier
numbers:
'X:{1} Y:{0}'.format(6, 7) # 'X:7 Y:6'
The system also accepts named identifiers, where the argument name is the same as the
name inside the curly brace where it is to be placed:
'X:{a} Y:{b}'.format(a=5, b=2) # 'X:5 Y:2'
Identifiers can also be a mixture of argument indices and names:
'X:{0} Y:{b}'.format(5, b=2) # 'X:5 Y:2'
If a sequence of values is passed in (e.g. a list or tuple), then the sequence can be
indexed inside the curly brace specification, so, for example, here the initial ‘0’ identifiers
refer to dList and the square brackets refer to the index of elements within that list.
dList = [5,7]
'X:{0[0]} Y:{0[1]}'.format(dList) # 'X:5 Y:7'
The sequence identifier can also be a named argument, which perhaps makes for more
readable code:
'X:{data[0]} Y:{data[1]}'.format(data=dList)
If the argument is a Python object then named attributes of that object can be used in
the braces:
import math
'Constant Pi:{0.pi}'.format(math) # 'Constant Pi:3.14159265359'
For the examples given so far we have let the formatting system display the values in a
standard, default manner. However, there are many additions that we can make to the
format specification inside the braces to control exactly how the output string should be
formatted. Hence, for example, we could repeat the above but display the floating point
number to only four decimal places using the formatting code after the colon:
'Constant Pi:{0.pi:.4f}'.format(math) # 'Constant Pi:3.1416'
The general form of the format specification is {
<:formatting>}. So, in the above example is ‘0.pi’, is not
specified and <:formatting> is ‘:.4f’. The part is generally not used, in which
case it is the equivalent of using the inbuilt str() function. If instead we use the ‘!r’ code
then the conversion is equivalent to repr(), which is especially handy if we have an object
that has a special string representation method (__repr__()) which is different from a plain
string conversion.
'Text: {0}'.format('abc') # Using str() - 'Text: abc'
'Text: {0!r}'.format('abc') # Using repr() - "Text: 'abc'"
The <:formatting> part of the specification itself may have several sub-components,
and the general form of this is <:(fill)align><0><#><,>
.
We will describe some of these options, although a more complete list of the possibilities
is listed in the table below.
An alignment code is used when the substring may be smaller than the insert width. In
such cases we can choose to align the value with the left, right or middle of the insert.
Here we use the ‘<’ code to push the value to the left of the insert and the value ‘5’ to
specify the width of the insert:
'Text:{0:<5}'.format('a') # 'Text:a '
Also, we could explicitly say that the insertion is of string type (which is the default
anyhow) using the ‘s’ data type code.
'Text:{0:<5s}'.format('a') # 'Text:a '
Similarly we could format to the right of the insert with a decimal integer (type code
‘d’) value, although right alignment is the default so need not be specified:
'Value:{0:>5d}'.format(-7) # 'Value: -7'
Or the alignment code ‘^’ could be used to place the value in the centre:
'Value:{0:^5d}'.format(7) # 'Value: 7 '
There is one further alignment option ‘=’, where any numeric sign is maximally
separated from a number:
'Value:{0:=5d}'.format(-7) # 'Value:- 7'
As standard, when we are aligning format values within a larger width, any extra room
is padded out with space characters. However, we may like to use something else as
padding, in which case a different padding character is placed before the alignment code.
So, for example, if we wanted to pad with asterisks:
'Value:{0:*>5d}'.format(7) # 'Value:****7'
Numeric signs will normally only be shown for negative numbers, but we can force the
appearance of a plus symbol for the positives with ‘+’ following the alignment code
(where present):
'Value:{0:>+5d}'.format(7) # 'Value: +7'
Likewise we can use a single space as a sign code, so that positive numbers have an
extra space before, which can be handy to keep alignment with negative numbers:
'Value:{0:< 6d}'.format(1023) #'Value: 1023 '
'Value:{0:< 6d}'.format(-1023) #'Value:-1023 '
Also for similar purposes, numeric values are easily padded with leading zeros to fill
the specified width:
'Value:{0:05d}'.format(123) # 'Value:00123'
A more recent addition to the scheme (from Python 2.7 onwards) is to use commas in
the format output to separate each ‘thousands’ block of three digits. As you might expect
this uses a ‘,’ code:
'Value:{0:,d}'.format(123456789) # 'Value:123,456,789' – Python 2.7+
A numeric value need not be specified as a decimal integer or floating point, as we have
shown so far. There are several other codes for different base systems, so, for example, we
can format as hexadecimal:
'Value:{0:4x}'.format(1023) # 'Value: 3ff'
For floating point numbers, as mentioned above, it is generally useful to specify the
precision (number of decimal places), which we achieve with the dot notation:
'Value:{0:.3f}'.format(123) # 'Value:123.000'
And as you may expect this can be combined with the required total width
specification. Here, for example, we make sure that at least ten characters are inserted for
a value specified to three decimal places:
'Value:{0:10.3f}'.format(123) # 'Value: 123.000'
As with the old-style formatting, floating point numbers can be represented in the
exponent format ‘e’:
'Value:{0:.2e}'.format(7) # 'Value:7.00e+00'
'Value:{0:.2e}'.format(0.0012) # 'Value:1.20e-03'
And also using the general number format ‘g’ which only uses the exponent form if the
exponent is small (< −4) or greater than the precision number:
'Value:{0:.4g}'.format(7.0) # 'Value:7'
'Value:{0:.4g}'.format(10234) # 'Value:1.023e+05'
It should be noted that the number of decimal places can be set dynamically from a
variable, should it need to change in a program. This can be achieved by having one
formatting code inside another. Hence here the number of decimal places is inserted into
the ‘{1}’ (from the second argument) to complete the outer formatting code, which in the
example below would be equivalent to ‘{0:.7f}’:
nPlaces = 7
'Value: {0:.{1}f}'.format(123, nPlaces) # 'Value: 123.0000000'
Lastly, we can use this tactic of having braces inside braces to control other aspects of a
format specification: here, for example, setting the alignment code with a named attribute:
'Value: {0:{align}5d}'.format(5, align='<') # 'Value: 5 '
The table below summarises the various alignment, sign and data type codes used with
Python’s new-style string formatting system.
0> Do'stlaringiz bilan baham: |