Python Format String

Field Width and Alignment

默认左对齐

'hey {:10}'.format('hello') Specify width (Aign left, fill with spaces)
'{:010}'.format(2) Fill with zeroesOutput: 0000000002
'{:*^30}'.format('text') Specify width, align to centerOutput: *************text*************
Option Meaning, padding
'<' Forces the field to be left-aligned within the available space (this is the default for most objects).
'>' Forces the field to be right-aligned within the available space (this is the default for numbers).
'=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width.
'^' Forces the field to be centered within the available space.

Member and Element Access

'{0}, {1}, {2}'.format(1, 2, 3) Access arguments by ordinal positionOutput: 1, 2, 3
'{}, {}, {}'.format(1, 2, 3) Implicit positional arguments (2.7 and above only)Output: 1, 2, 3
'{value1}, {value2}, {value2}'.format(value1=1, value2=2, value3=3) Access keyword arguments by nameOutput: 1, 2, 2
'{[1]}'.format(['first', 'second', 'third']) Access element by indexOutput: second
'{.name}'.format(sys.stdin) Access element attributeOutput: <stdin>
'{[name]}'.format({'name': 'something'}) Access element by keyOutput: something

Numerical Representation

'{:x}'.format(100) Hexadecimal representationOutput: 64
'{:X}'.format(3487) Hexadecimal representation (uppercase letters)Output: D9F
'{:#x}'.format(100) Hexadecimal representation (including the 0x)Output: 0x64
'{:b}'.format(100) Binary representationOutput: 1100100
'{:c}'.format(100) Character representationOutput: d
'{:d}'.format(100) Decimal representation (default)Output: 100
'{:,}'.format(1000000) With thousands separatorOutput: 1,000,000
'{:o}'.format(100) Octal representationOutput: 144
'{:n}'.format(100) Like d, but uses locale information for separatorsOutput: 100
'{:e}'.format(0.0000000001) Exponent notationOutput: 1.000000e-10
'{:E}'.format(0.0000000001) Exponent notation (capital ‘E’)Output: 1.000000E-10
'{:f}'.format(3/14.0) Fixed pointOutput: 0.214286
'{:g}'.format(3/14.0) General formatOutput: 0.214286
'{:%}'.format(0.66) PercentageOutput: 66.000000%
'{:.3}'.format(0.214286) PrecisionOutput: 0.214

Integers

Type Meaning
'b' Binary format. Outputs the number in base 2.
'c' Character. Converts the integer to the corresponding unicode character before printing.
'd' Decimal Integer. Outputs the number in base 10.
'o' Octal format. Outputs the number in base 8.
'x' Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9.
'X' Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9.
'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters.
None The same as 'd'.

Floating numbers

Type Meaning
'e' Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent. The default precision is 6.
'E' Exponent notation. Same as 'e' except it uses an upper case ‘E’ as the separator character.
'f' Fixed-point notation. Displays the number as a fixed-point number. The default precision is 6.
'F' Fixed-point notation. Same as 'f', but converts nan to NAN and inf to INF.
'g' General format. For a given precision p >= 1, this rounds the number to psignificant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4<= exp < p, the number is formatted with presentation type 'f' and precisionp-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6.
'G' General format. Same as 'g' except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too.
'n' Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.
'%' Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.
None Similar to 'g', except that fixed-point notation, when used, has at least one digit past the decimal point. The default precision is as high as needed to represent the particular value. The overall effect is to match the output of str() as altered by the other format modifiers.

Conversions

'{!r}'.format('string') Calling repr on argumentsOutput: 'string'
'{!s}'.format(1.53438987) Calling str on argumentsOutput: 1.53438987

Number Formattting

The following table shows various ways to format numbers using Python’s str.format(), including examples for both float formatting and integer formatting.

To run examples use print("FORMAT".format(NUMBER));
So to get the output of the first example, you would run: print("{:.2f}".format(3.1415926));

Number Format Output Description
3.1415926 {:.2f} 3.14 2 decimal places
3.1415926 {:+.2f} +3.14 2 decimal places with sign
-1 {:+.2f} -1.00 2 decimal places with sign
2.71828 {:.0f} 3 No decimal places
5 {:0>2d} 05 Pad number with zeros (left padding, width 2)
5 {:x<4d} 5xxx Pad number with x’s (right padding, width 4)
10 {:x<4d} 10xx Pad number with x’s (right padding, width 4)
1000000 {:,} 1,000,000 Number format with comma separator
0.25 {:.2%} 25.00% Format percentage
1000000000 {:.2e} 1.00e+09 Exponent notation
13 {:10d} 13 Right aligned (default, width 10)
13 {:<10d} 13 Left aligned (width 10)
13 {:^10d} 13 Center aligned (width 10)

Official Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 1) by position:
'{0}, {1}, {2}'.format('a', 'b', 'c')
'{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
'{2}, {1}, {0}'.format('a', 'b', 'c')
'{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
'{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated

#2) by name
'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
'Coordinates: {latitude}, {longitude}'.format(**coord)

#3) by attributes
c = 3-5j
('The complex number {0} is formed from the real part {0.real} '
'and the imaginary part {0.imag}.').format(c)

class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return 'Point({self.x}, {self.y})'.format(self=self)
str(Point(4, 2))

#4) by arguments' items
coord = (3, 5)
'X: {0[0]}; Y: {0[1]}'.format(coord)

#5) 注意这里的aligned用了> < Y与regex的look around保持一直
'{:<30}'.format('left aligned')
'{:>30}'.format('right aligned')
'{:^30}'.format('centered')
'{:*^30}'.format('centered') # use '*' as a fill char

#6) Replacing %+f, %-f, and % f and specifying a sign:
'{:+f}; {:+f}'.format(3.14, -3.14) # show it always
'{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
'{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'

# 7) Replacing %x and %o and converting the value to different bases:
# format also supports binary numbers
"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
# with 0x, 0o, or 0b as prefix:
"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)

Other Examples

Padding and aligning strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#alight right 
'%10s' % ('test',)
'{:>10}'.format('test')
test
#align left:
'%-10s' % ('test',)
'{:10}'.format('test')
'{:10}'.format('test')
test
#new style
'{:_<10}'.format('test')
test______

#new style
'{:^10}'.format('test')

Truncating Long Strings

1
2
3
'%.5s' % ('xylophone',) #注意后面的小数点呀是truncate 
'{:.5}'.format('xylophone')
xylop

Combining truncating and padding

1
2
3
'%-10.5s' % ('xylophone',)
'{:10.5}'.format('xylophone')
xylop

Numbers

1
2
3
4
5
6
7
8
9
10
11
'%d' % (42,)
'{:d}'.format(42)
42

'%f' % (3.141592653589793,)
'{:f}'.format(3.141592653589793)
3.141593

#signed numbers
'%+d' % (42,)
'{:+d}'.format(42)

Getitem and Getattr

1
2
3
4
5
6
person = {'first': 'Jean-Luc', 'last': 'Picard'}
'{p[first]} {p[last]}'.format(p=person)
class Plant(object):
type = 'tree'
'{p.type}'.format(p=Plant())
'{:{align}{width}}'.format('test', align='^', width='10')

Datetime

1
2
from datetime import datetime
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))