在python中,我想格式化一个字符串,组合两个字符串和百分比。从这篇文章how to show Percentage in python我知道格式化我们可以使用的百分比
>>> print "{:.0%}".format(1/3)
33%
在我的情况下,我想做点什么
>>> print "{0}/{1} = {:.0%}".format('1', '3', 1/3)
1/3 = 33%
但上面的代码返回
ValueError: cannot switch from manual field specification to automatic field numbering
那么格式化字符串的正确方法是什么?谢谢!
它的含义是你为前两个参数{0}
和{1}
提供编号的位置,然后突然有一个没有定位号,所以它不能推断放在那里的那个。 (如编号时,它们可以是任何顺序或重复)所以你需要确保最后一项也是编号。
print "{0}/{1} = {2:.0%}".format('1', '3', 1/3)
或者,让它计算出格式参数的位置:
print("{}/{} = {:.0%}".format('1', '3', 1/3))
在Python2.7中
>>> print "{:.0%}".format(1/3)
0%
我想它应该是不受支持的百分比
在python3.5中
可以正常工作
>>> print("{}/{} = {:.0%}".format('1', '3', 1/3))
1/3 = 33%
>>> print("{0}/{1} = {2:.0%}".format('1', '3', 1/3))
1/3 = 33%
所以,两种写法不能混为一谈