Tuesday, January 29, 2019

Python string format quick guide

This is a quick summary guide for when you just want to remind yourself how to format a value with Python's 'string'.format().


Curly brackets are used to refer to parameter values in the 'format' method. On their own, the first pair of curly brackets will refer to the first parameter, second to the second, etc.

'{} {} {}'.format('a', 1, True)
a 1 True

Alternatively you can specify which parameter you want to use where using indexes.

'{0} {0} {2}'.format('a', 1, True)
a a True

You can even use names instead of indexes.

'{a} {b} {c}'.format(a='a', b=1, c=True)
a 1 True

And even refer to indexes in lists and to instance variables in objects.

'{a[0]} {b.numerator}'.format(a=[3,1,2], b=fractions.Fraction(1,2))
3 1


Adding a colon inside the curly brackets allows you to format the values before they are added to the string. You can combine these with any of the above methods of referencing. The following formatting meta characters are to be used in the following order:
{:[alignment] [grouping] [precision] [data type]}

Aligning/padding/leading zeros
An alignment meta character is either >, <, or ^. The number after it is the field width in which to align.

'|{:>3}|{:<3}|{:^3}|'.format('a', 'b', 'c')
|  a|b  | c |

Any character before the alignment meta character is used instead of spaces.
'{:_>5} {:0>5}'.format('a', 12)
____a 00012

You can group digits in numbers into triples with commas automatically by just putting a comma in the curly brackets.


When formatting floats you can specify how many digits to keep after the point by adding a dot and a number. By default the format of the number is in scientific notation which means that your floating point number will look like 12e-4 with the precision referring to the number of digits in the mantissa (the number before 'e'). See the next section to format your number in fixed point notation.


Data types
This is the most important part. The data type always comes at the end and is a single letter.

You can use it to change the numeric base of a whole number.
'dec-{:d} hex-{:X} oct-{:o} bin-{:b}'.format(16, 16, 16, 16)
dec-16 hex-10 oct-20 bin-10000

You can use it to convert unicode values to characters.

You can use it to convert numbers into scientific notations,

or fixed point notations,

or percentages.

Mixed examples