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.
Code | Value |
---|---|
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:
Kod | Värde | Kommentar |
---|---|---|
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. |
- The format codes are written after the colon within the curley brackets.
- The code
d
specifies integer in decimal form. - The code
f
specifies floating point number in decimal form. - The code
e
specifies floating point number in scientific (exponential) form. - The field width can be specified after the letter code.
- The positioning in the field can be specified by
<
and^
. Right positioning id default but can alse be specified by>
. - For floating point values the number of decimal can be specified after a decimal point.
The format
method
The same example as above but with the format
method in the string
class:
Code | Value |
---|---|
'{}'.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' |
format
-method.
Formatting with %
-operator
Exemple:
Code | Value |
---|---|
'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.