Python 2.7.3
>>> print '%2.2f' % 0.1
0.10
我所说的文档说类型%应该与类型f相同,只是输入乘以100。
>>> print '%2.2%' % 0.1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
答案 0 :(得分:3)
使用新格式表达式,其中包含您所指的格式化程序
print "{:%}".format(0.1)
#10.000000%
如果你只想要整数部分,你可以使用精度规范
print "{:.0%}".format(0.1)
#10%
请参阅
上的文档http://docs.python.org/2/library/string#formatspec
为了扩展一点,新格式指定器实际上比旧格式更强大。首先,按顺序或名称调用参数非常简单
"play the {instrument} all {moment}, even if my {instrument} is old".format(moment='day', instrument='guitar')
#'play the guitar all day, even if my guitar is old'
然后,从文档中可以看出,可以访问对象的属性:
"the real component is {0.real} and the imaginary one is {0.imag}".format(3+4j)
#'the real component is 3.0 and the imaginary one is 4.0'
除此之外还有很多,但你可以在文档中找到它,非常清楚。
答案 1 :(得分:0)
print '%2.2%' % 0.1
告诉它格式字符串(%)中有2个占位符,所以你有一个抱怨