Reputation: 863
In python, I want to format a string combining two strings with a percentage. From this post how to show Percentage in python I know to format a percentage we can use
>>> print "{:.0%}".format(1/3)
33%
In my case I want to do something like
>>> print "{0}/{1} = {:.0%}".format('1', '3', 1/3)
1/3 = 33%
But the above code returns
ValueError: cannot switch from manual field specification to automatic field numbering
So what's the proper way to format the string like this? Thank you!
Upvotes: 2
Views: 405
Reputation: 175
In Python2.7
>>> print "{:.0%}".format(1/3)
0%
I guess it should be unsupported percentage
In python3.5
can work normally
>>> print("{}/{} = {:.0%}".format('1', '3', 1/3))
1/3 = 33%
>>> print("{0}/{1} = {2:.0%}".format('1', '3', 1/3))
1/3 = 33%
so, two ways to write can not be mixed
Upvotes: 1
Reputation: 6160
What is it saying is that you are providing numbered placement for the first two arguments {0}
and {1}
, then suddenly there is one without a positioning number, so it cannot extrapolate which one to put there. (As when numbered, they can be in any order or repeat) So you need to make sure that last item is also numbered.
print "{0}/{1} = {2:.0%}".format('1', '3', 1/3)
Alternatively, let it figure the positioning of the format arguments out:
print("{}/{} = {:.0%}".format('1', '3', 1/3))
Upvotes: 2