在Python中,我们如何组合字符串和百分比的格式化机制?

问题描述 投票:2回答:2

在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

那么格式化字符串的正确方法是什么?谢谢!

python string format percentage
2个回答
2
投票

它的含义是你为前两个参数{0}{1}提供编号的位置,然后突然有一个没有定位号,所以它不能推断放在那里的那个。 (如编号时,它们可以是任何顺序或重复)所以你需要确保最后一项也是编号。

print "{0}/{1} = {2:.0%}".format('1', '3', 1/3)

或者,让它计算出格式参数的位置:

print("{}/{} = {:.0%}".format('1', '3', 1/3))

1
投票

在Python2.7中

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

我想它应该是不受支持的百分比

在python3.5中

可以正常工作

  1. 有位置参数
>>> print("{}/{} = {:.0%}".format('1', '3', 1/3))
1/3 = 33%
  1. 没有位置参数
>>> print("{0}/{1} = {2:.0%}".format('1', '3', 1/3))
1/3 = 33%

所以,两种写法不能混为一谈

© www.soinside.com 2019 - 2024. All rights reserved.