Python string format snippets

About

Documentation

Import directives


In [ ]:
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 [ ]:
"{:03}".format(1)

In [ ]:
"{:.<9}".format(3)

In [ ]:
"{:.<9}".format(11)

In [ ]:
"{:.>9}".format(3)

In [ ]:
"{:.>9}".format(11)

In [ ]:
"{:.=9}".format(3)

In [ ]:
"{:.=9}".format(11)

In [ ]:
"{:.^9}".format(3)

In [ ]:
"{:.^9}".format(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 [ ]:
"{:+}".format(3)

In [ ]:
"{:+}".format(-3)

In [ ]:
"{:-}".format(3)

In [ ]:
"{:-}".format(-3)

In [ ]:
"{: }".format(3)

In [ ]:
"{: }".format(-3)

Width


In [ ]:
"{:3}".format(3)

In [ ]:
"{:3}".format(11)

Precision


In [ ]:
"{}".format(math.pi)

In [ ]:
"{:.2f}".format(math.pi)

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 [ ]:
"{:9.4f}".format(math.pi)

In [ ]:
"{:9.4f}".format(12.123456789)

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 [ ]:
"{:}".format(21)

In [ ]:
"{:b}".format(21)

In [ ]:
"{:#b}".format(21)

In [ ]:
"{:c}".format(21)

In [ ]:
"{:d}".format(21)

In [ ]:
"{:o}".format(21)

In [ ]:
"{:#o}".format(21)

In [ ]:
"{:x}".format(21)

In [ ]:
"{:X}".format(21)

In [ ]:
"{:#x}".format(21)

In [ ]:
"{:#X}".format(21)

In [ ]:
"{:n}".format(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 [ ]:
"{}".format(math.pi)

In [ ]:
"{:e}".format(math.pi)

In [ ]:
"{:E}".format(math.pi)

In [ ]:
"{:f}".format(math.pi)

In [ ]:
"{:F}".format(math.pi)

In [ ]:
"{:g}".format(math.pi)

In [ ]:
"{:G}".format(math.pi)

In [ ]:
"{:n}".format(math.pi)

In [ ]:
"{:%}".format(math.pi)

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


In [ ]:
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))

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


In [ ]:
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))

More examples with {:g}


In [ ]:
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))

In [ ]:
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))

In [ ]: