Python string format snippets

Jérémie Decock (www.jdhp.org)

About

Documentation

Import directives

In [1]:
import math

Short documentation

"{field_name:format_spec}".format(...)

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]

fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
  • The '#' option:
    • Is only valid for integers, and only for binary, octal, or hexadecimal output.
    • If present, it specifies that the output will be prefixed by '0b', '0o', or '0x
  • The ',' option:
    • Signals the use of a comma for a thousands separator.
    • For a locale aware separator, use the 'n' integer presentation type instead.

Fill and align

  • '<' : 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.
  • '^' : Forces the field to be centered within the available space.
In [2]:
"{:03}".format(1)
Out[2]:
'001'
In [3]:
"{:.<9}".format(3)
Out[3]:
'3........'
In [4]:
"{:.<9}".format(11)
Out[4]:
'11.......'
In [5]:
"{:.>9}".format(3)
Out[5]:
'........3'
In [6]:
"{:.>9}".format(11)
Out[6]:
'.......11'
In [7]:
"{:.=9}".format(3)
Out[7]:
'........3'
In [8]:
"{:.=9}".format(11)
Out[8]:
'.......11'
In [9]:
"{:.^9}".format(3)
Out[9]:
'....3....'
In [10]:
"{:.^9}".format(11)
Out[10]:
'...11....'

Sign

  • '+' : indicates that a sign should be used for both positive as well as negative numbers.
  • '-' : indicates that a sign should be used only for negative numbers (this is the default behavior).
  • space : indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.
In [11]:
"{:+}".format(3)
Out[11]:
'+3'
In [12]:
"{:+}".format(-3)
Out[12]:
'-3'
In [13]:
"{:-}".format(3)
Out[13]:
'3'
In [14]:
"{:-}".format(-3)
Out[14]:
'-3'
In [15]:
"{: }".format(3)
Out[15]:
' 3'
In [16]:
"{: }".format(-3)
Out[16]:
'-3'

Width

In [17]:
"{:3}".format(3)
Out[17]:
'  3'
In [18]:
"{:3}".format(11)
Out[18]:
' 11'

Precision

In [19]:
"{}".format(math.pi)
Out[19]:
'3.141592653589793'
In [20]:
"{:.2f}".format(math.pi)
Out[20]:
'3.14'

Width + Precision

In the following examples, 9 is the total space for the number (i.e. including dot and decimals) thus the following example has 4 characters for decimals, one character for the dot and 4 remaining characters for integers.

In [21]:
"{:9.4f}".format(math.pi)
Out[21]:
'   3.1416'
In [22]:
"{:9.4f}".format(12.123456789)
Out[22]:
'  12.1235'

Type

Iteger

The available integer presentation types are:

  • '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'.
In [23]:
"{:}".format(21)
Out[23]:
'21'
In [24]:
"{:b}".format(21)
Out[24]:
'10101'
In [25]:
"{:#b}".format(21)
Out[25]:
'0b10101'
In [26]:
"{:c}".format(21)
Out[26]:
'\x15'
In [27]:
"{:d}".format(21)
Out[27]:
'21'
In [28]:
"{:o}".format(21)
Out[28]:
'25'
In [29]:
"{:#o}".format(21)
Out[29]:
'0o25'
In [30]:
"{:x}".format(21)
Out[30]:
'15'
In [31]:
"{:X}".format(21)
Out[31]:
'15'
In [32]:
"{:#x}".format(21)
Out[32]:
'0x15'
In [33]:
"{:#X}".format(21)
Out[33]:
'0X15'
In [34]:
"{:n}".format(21)
Out[34]:
'21'

Float

The available presentation types for floating point and decimal values are:

  • '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. Displays the number as a fixed-point number. The default precision is 6.
  • 'F' : Fixed point. Same as 'f'.
  • 'g' : General format.
    • For a given precision p >= 1, this rounds the number to p significant 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 precision p-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 : The same as 'g'.
In [35]:
"{}".format(math.pi)
Out[35]:
'3.141592653589793'
In [36]:
"{:e}".format(math.pi)
Out[36]:
'3.141593e+00'
In [37]:
"{:E}".format(math.pi)
Out[37]:
'3.141593E+00'
In [38]:
"{:f}".format(math.pi)
Out[38]:
'3.141593'
In [39]:
"{:F}".format(math.pi)
Out[39]:
'3.141593'
In [40]:
"{:g}".format(math.pi)
Out[40]:
'3.14159'
In [41]:
"{:G}".format(math.pi)
Out[41]:
'3.14159'
In [42]:
"{:n}".format(math.pi)
Out[42]:
'3.14159'
In [43]:
"{:%}".format(math.pi)
Out[43]:
'314.159265%'

Comparison between {:f}, {:e} and {:g}

In [44]:
numbers = [1000000, 100000, 10000, 1000, 100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001]
for number in numbers:
    print("{:f}".format(number), end="\t")
    print("{:e}".format(number), end="\t")
    print("{:g}".format(number))
1000000.000000	1.000000e+06	1e+06
100000.000000	1.000000e+05	100000
10000.000000	1.000000e+04	10000
1000.000000	1.000000e+03	1000
100.000000	1.000000e+02	100
10.000000	1.000000e+01	10
1.000000	1.000000e+00	1
0.100000	1.000000e-01	0.1
0.010000	1.000000e-02	0.01
0.001000	1.000000e-03	0.001
0.000100	1.000000e-04	0.0001
0.000010	1.000000e-05	1e-05

Comparison between {:f}, {:e} and {:g} with a precision of 2

In [45]:
numbers = [1000, 100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001]
for number in numbers:
    print("{:.2f}".format(number), end="\t\t")
    print("{:.2e}".format(number), end="\t")
    print("{:.2g}".format(number))
1000.00		1.00e+03	1e+03
100.00		1.00e+02	1e+02
10.00		1.00e+01	10
1.00		1.00e+00	1
0.10		1.00e-01	0.1
0.01		1.00e-02	0.01
0.00		1.00e-03	0.001
0.00		1.00e-04	0.0001
0.00		1.00e-05	1e-05

More examples with {:g}

In [46]:
numbers = [1000, 100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001]
for number in numbers:
    print("{:g}".format(number), end="\t")
    print("{:.3g}".format(number), end="\t")
    print("{:.2g}".format(number), end="\t")
    print("{:.1g}".format(number), end="\t")
    print("{:.0g}".format(number))
1000	1e+03	1e+03	1e+03	1e+03
100	100	1e+02	1e+02	1e+02
10	10	10	1e+01	1e+01
1	1	1	1	1
0.1	0.1	0.1	0.1	0.1
0.01	0.01	0.01	0.01	0.01
0.001	0.001	0.001	0.001	0.001
0.0001	0.0001	0.0001	0.0001	0.0001
1e-05	1e-05	1e-05	1e-05	1e-05
In [47]:
numbers = [1234000, 123400, 12340, 1234, 123.4, 12.34, 1.234, 0.1234, 0.01234, 0.001234, 0.0001234, 0.00001234]
for number in numbers:
    print("{:<10g}".format(number), end="\t")
    print("{:<10.6g}".format(number), end="\t")
    print("{:<10.5g}".format(number), end="\t")
    print("{:<10.4g}".format(number), end="\t")
    print("{:<10.3g}".format(number), end="\t")
    print("{:<10.2g}".format(number), end="\t")
    print("{:<10.1g}".format(number))
1.234e+06 	1.234e+06 	1.234e+06 	1.234e+06 	1.23e+06  	1.2e+06   	1e+06     
123400    	123400    	1.234e+05 	1.234e+05 	1.23e+05  	1.2e+05   	1e+05     
12340     	12340     	12340     	1.234e+04 	1.23e+04  	1.2e+04   	1e+04     
1234      	1234      	1234      	1234      	1.23e+03  	1.2e+03   	1e+03     
123.4     	123.4     	123.4     	123.4     	123       	1.2e+02   	1e+02     
12.34     	12.34     	12.34     	12.34     	12.3      	12        	1e+01     
1.234     	1.234     	1.234     	1.234     	1.23      	1.2       	1         
0.1234    	0.1234    	0.1234    	0.1234    	0.123     	0.12      	0.1       
0.01234   	0.01234   	0.01234   	0.01234   	0.0123    	0.012     	0.01      
0.001234  	0.001234  	0.001234  	0.001234  	0.00123   	0.0012    	0.001     
0.0001234 	0.0001234 	0.0001234 	0.0001234 	0.000123  	0.00012   	0.0001    
1.234e-05 	1.234e-05 	1.234e-05 	1.234e-05 	1.23e-05  	1.2e-05   	1e-05     
In [48]: