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().

Referencing

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

Formatting

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

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

'{:,}'.format(12345678)
12,345,678

Precision
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.

'{:.3}'.format(12345678.0)
1.23e+07

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.
'{:c}'.format(97)
a

You can use it to convert numbers into scientific notations,
'{:e}'.format(12345678)
1.234568e+07

or fixed point notations,
'{:f}'.format(12345678)
12345678.000000

or percentages.
'{:%}'.format(0.1234)
12.340000%

Mixed examples

'{:0>2X}'.format(10)
0A

'{:,d}'.format(1234567)
1,234,567

'{:,.2f}'.format(12345.6)
12,345.60

'{:.2%}'.format(0.1234)
12.34%

No comments:

Post a Comment