Reputation: 53
I'm new to python, recently I have migrated to Python 3 and
I'm trying to get used to the format()
function.
What I'm trying to do is to print()
the temperature I create
in floating-points, like so:
temperature = [23, 24, 25, 26, 27]
print("Today's temperature is %.02f" % (temperature[0]))
Instead of using %.02f
, I would like to know how
that could be written in the format()
function instead
of the %
percentage.
Upvotes: 1
Views: 12502
Reputation: 1396
As of Python 3.6, you can use f-strings for such formatting:
>>> temperature = [23, 24, 25, 26, 27]
>>> print(f'Temperature is: {temperature[0]:.2f}')
Temperature is: 23.00
Upvotes: 2
Reputation: 52081
You will have to use {:.02f}
>>> temperature = [23, 24, 25, 26, 27]
>>> print("Today's temperature is %.02f" % (temperature[0]))
Today's temperature is 23.00
>>> print("Today's temperature is {:.02f}".format(temperature[0]))
Today's temperature is 23.00
More information can be found in the documentation. However do see Format Examples
'%03.2f'
can be translated to'{:03.2f}'
Upvotes: 5