Formatting

Format Mini-language

Format

F-strings: Literal String Interpolation

PEP 498 The new f-strings in Python 3.6

>>> import datetime
>>> name = 'Fred'
>>> age = 50
>>> anniversary = datetime.date(1991, 10, 12)
>>> f'My name is {name}, my age next year is {age+1}, my anniversary is {anniversary:%A, %B %d, %Y}.'
'My name is Fred, my age next year is 51, my anniversary is Saturday, October 12, 1991.'
>>> f'He said his name is {name!r}.'
"He said his name is 'Fred'."

'f' may be combined with 'r' or 'R', in either order, to produce raw f-string literals

The parts of the f-string outside of braces are literal strings. These literal portions are then decoded. For non-raw f-strings, this includes converting backslash escapes such as '\n', '\"', "\'", '\xhh', '\uxxxx', '\Uxxxxxxxx', and named unicode characters '\N{name}' into their associated Unicode characters [6].

Backslashes may not appear anywhere within expressions. Comments, using the '#' character, are not allowed inside an expression.

Format specifiers

Format specifiers may also contain evaluated expressions. This allows code such as:

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result:      12.35'

%-string

%-formatting is limited as to the types it supports. Only ints, strs, and doubles can be formatted. All other types are either not supported, or converted to one of these types before formatting. In addition, there's a well-known trap where a single value is passed:

>>> msg = 'disk failure'
>>> 'error: %s' % msg
'error: disk failure'

But if msg were ever to be a tuple, the same code would fail:

>>> msg = ('disk failure', 32)
>>> 'error: %s' % msg
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

To be defensive, the following code should be used:

>>> 'error: %s' % (msg,)
"error: ('disk failure', 32)"

string.format

>>> value = 4 * 20
>>> 'The value is {value}.'.format(value=value)
'The value is 80.'

Underscores in Numeric Literals

PEP515 Python 3.6

PEP 515 adds the ability to use underscores in numeric literals for improved readability. For example:

>>> 1_000_000_000_000_000
1000000000000000
>>> 0x_FF_FF_FF_FF
4294967295

Single underscores are allowed between digits and after any base specifier. Leading, trailing, or multiple underscores in a row are not allowed.

The string formatting language also now has support for the '_' option to signal the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type 'd'. For integer presentation types 'b', 'o', 'x', and 'X', underscores will be inserted every 4 digits:

>>> '{:_}'.format(1000000)
'1_000_000'
>>> '{:_x}'.format(0xFFFFFFFF)
'ffff_ffff'

Unicode

Python 3

If you can’t enter a particular character in your editor or want to keep the source code ASCII-only for some reason, you can also use escape sequences in string literals. (Depending on your system, you may see the actual capital-delta glyph instead of a u escape.)

>>> "\N{GREEK CAPITAL LETTER DELTA}"  # Using the character name
'\u0394'
>>> "\u0394"                          # Using a 16-bit hex value
'\u0394'
>>> "\U00000394"                      # Using a 32-bit hex value
'\u0394'

Output Colour

Termcolor