Hang Chen
Hang Chen

Reputation: 863

In Python how can we combine the formatting mechanism for both strings and a percentage?

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

Answers (2)

sunnky
sunnky

Reputation: 175

In Python2.7

>>> print "{:.0%}".format(1/3)
0%

I guess it should be unsupported percentage

In python3.5

can work normally

  1. with positional parameters
>>> print("{}/{} = {:.0%}".format('1', '3', 1/3))
1/3 = 33%
  1. no positional parameters
>>> print("{0}/{1} = {2:.0%}".format('1', '3', 1/3))
1/3 = 33%

so, two ways to write can not be mixed

Upvotes: 1

CasualDemon
CasualDemon

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

Related Questions