Python output percentages in two ways
Note: Test under the PYTHON3 environment.
Mode 1: Direct use of parameter formatting: {:.2%}
{:.2%}
: Show 2 digits after decimal point
- Show 2 digits after the decimal point:
print(‘percent: {:.2%}‘.format(42/50))percent: 84.00%
- Do not display decimal digits:
{:.0%}
, that is, will be 2
changed to 0
:
print(‘percent: {:.0%}‘.format(42/50))percent: 84%
Mode 2: Format to float and then process into% format: {:.2f}%
The difference from Mode 1 is:
(1) to 42/50
multiply by 100.
(2) on the outside of Mode 2 %
{ }
, Mode 1 is inside %
{ }
.
- Show 2 digits after the decimal point:
print(‘percent: {:.2f}%‘.format(42/50*100))percent: 84.00%
- Show 1 digits after the decimal point:
print(‘percent: {:.1f}%‘.format(42/50*100))percent: 84.0%
- Show only integer digits:
print(‘percent: {:.0f}%‘.format(42/50*100))percent: 84%
Description
{ }
Corresponds to format()
a parameter, in the default order corresponding to the parameter ordinal starting from 0, {0}
corresponding to format()
the first parameter, corresponding to the {1}
second parameter. For example:
print(‘percent1: {:.2%}, percent2: {:.1%}‘.format(42/50, 42/100))percent1: 84.00%, percent2: 42.0%
- Specify the Order:
{1:.1%}
Corresponds to the 2nd parameter, corresponding to the {0:.1%}
1th parameter.
print(‘percent2: {1:.1%}, percent1: {0:.1%}‘.format(42/50, 42/100))percent2: 42.0%, percent1: 84.0%
Python output percentages in two ways