在 Python 中,我们如何结合字符串和百分比的格式化机制?
In Python how can we combine the formatting mechanism for both strings and a percentage?
在 python 中,我想格式化一个将两个字符串与百分比组合在一起的字符串。从这个 post how to show Percentage in python 我知道要格式化我们可以使用的百分比
>>> print "{:.0%}".format(1/3)
33%
就我而言,我想做类似
的事情
>>> print "{0}/{1} = {:.0%}".format('1', '3', 1/3)
1/3 = 33%
但是上面的代码returns
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%
所以,两种写法不能混用
在 python 中,我想格式化一个将两个字符串与百分比组合在一起的字符串。从这个 post how to show Percentage in python 我知道要格式化我们可以使用的百分比
>>> print "{:.0%}".format(1/3)
33%
就我而言,我想做类似
的事情>>> print "{0}/{1} = {:.0%}".format('1', '3', 1/3)
1/3 = 33%
但是上面的代码returns
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%
所以,两种写法不能混用