You can specify the number of decimal places before %:
>>> f'{0.123:.2%}'
'12.30%'
Answer from Lord Elrond on Stack OverflowVideos
There are two ways of string formatting in python and I've been consistently using the percentage (%) method until now:
"Today is %s." % datetime.now() # 2018-06-03 16:50:35.226194 "%d is a good number." % 5 # 5
I know this may not be very eloquent, but does the job well. One of the major irritants for me is the number to string conversion, I've faced that error so many times in the earlier days when I simply used to "There are " + x + " mangoes.". This works great in most other languages as they "auto-convert" the x from integer to string, but not python because of its "explicitness". But today, I learned of this new method of string.format() which does the same job, perhaps more eloquently:
"Today is {0}.".format(datetime.now()) # 2018-06-03 16:50:35.226194
"{0} is a good number.".format(5) # 5The only problem I'd imagine would be when you have to deal with long floats:
f = 1.234535666
"this is a floating point number: {0}".format(f) # 1.234535666Problem here is that it will output the entire float as it is without rounding, and here is where my percentage method has an edge!
"this is a floating point number: %.2f" % f # 1.23
Firstly, you can write e. g. {0:.2f} to specify a float with 2 decimals, see e. g. https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3
Secondly, the best formatting method is f-strings, see e. g. https://www.blog.pythonlibrary.org/2018/03/13/python-3-an-intro-to-f-strings/
of course .format() can do number formatting - "a number {:.2f}"! also you don't have to use explicit {0} indexing, you can go by position {} or use labels {a}.
https://docs.python.org/3.4/library/string.html#format-examples
You just discovered .format()? people are mostly migrating away from that to fstrings if they are using modern versions.
dude, you have to read the docs