I am calculating the percentage and I need the symbol % to remain in the string
def porcentaje(divisor, numerador):
return '%s%' % (round(float(divisor) / float(numerador) * 100, 2))
This is the function I am using, but it gives me an error of
incomplete format
How can i fix this.
Thanks to everyone beforehand
The error is obviously because it understands that the second
%
is a replacement flag when formatting the string. You must escape this character, to do this just put another one%
in front of it:note that you can use the formatting itself for rounding:
However, if you're using Python >= 3.6 I recommend using formatted string literals and not the old formatting via
%
, it's more readable and even more efficient:format()
/str.format
is also another possibility that works in previous versions of Python 3 and Python 2.7 as well. It has a small performance handicap compared to the previous ones due to the method call, although it is also the most flexible:in this case the builtin
format
is a better option for efficiency thanstr.format
, although it can obviously also be used:The format specifiers used are:
.2f
treats the numeric value as a float and rounds to two decimal places..2%
for its part, it multiplies the value by 100, rounds to two decimal places and displays the symbol%
at the end.For more information on the possibilities offered by f-string and
format
I recommend you look at the Format specification minilanguage