Formatting: Convertering numbers to strings

There are several ways to convert numbers (i.e. data types used for arithmetic) to strings (i.e. sequences of digits). The most modern way is to use so called f-strings.

f-strings

Suppose the two variables n and x ar set to 12 and 2/3 respectively, i.e. one value of integer type and one value of floating point type.

Exemple of conversions of these numbers:
CodeValue
f'{n}' '12'
f'n = {n}' 'n = 12'
f'{n} squared is {n*n}' '12 squared is 144'
f'{x}' '0.6666666666666666'
f'x squared is {x**2}' 'x squared is 0.4444444444444444'

Thus, in f-strings you can write expressions enclosed by curely brackets. These expressions are evaluated to values afterwards converted to strings.

It is possible to specify details like field width, justification and number of decimals by providing format codes.

The same examples as above with n and x but with format codes:

KodVärdeKommentar
f'{n:6d}' ' 12' Integer, 6 positions, right adjusted.
f'{n:<6d}' '12 ' Integer, 6 positions, left adjusted.
f'{n:^6d}' ' 12 ' Integer, 6 positions, centered.
f'{x:.3f}' '0.667' Floating point number, 3 decimals.
f'{x:10.4f}' ' 0.6667' Floating point number, 4 decimals, right adjusted in 10 positions.
f'{x:.5e}' '6.66667e-01' Floting point number in scientific format, 5 decimals.
Thus:

The format method

The same example as above but with the format method in the string class:
CodeValue
'{}'.format(n) '12'
'n = {}'.format(n) 'n = 12'
'{} squared is {}'.format(n, n*n) '12 squared is 144'
'{}'.format(x) '0.6666666666666666'
'{:6d}'.format(n) ' 12'
'{:<6d}'.format(n) '12 '
'{:^6d}'.format(n) ' 12 '
'{:.3f}'.format(x) '0.667'
'{:10.4f}'.format(x) ' 0.6667'
'{:.5e}'.format(x) '6.66667e-01'
Thus, here you specify the values to be converted as arguments to format-method.

Formatting with %-operator

Exemple:
CodeValue
'n = %d, x = %5.2f' % (n, x) 'n = 12, x = 0.67'

Here the fomat codes are written after % within the string. The character % is also used as an operator on a string and a tuple.

This method is often seen in older code but the methods above are much better.

Valid CSS!