蟒蛇 2.7.3
>>> print '%2.2f' % 0.1
0.10
Run Code Online (Sandbox Code Playgroud)
我的文档说类型 % 应该与类型 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
Run Code Online (Sandbox Code Playgroud)
使用新的格式表达式,其中包含您所指的格式化程序
print "{:%}".format(0.1)
#10.000000%
Run Code Online (Sandbox Code Playgroud)
如果你只想要整数部分,你可以使用精度规范
print "{:.0%}".format(0.1)
#10%
Run Code Online (Sandbox Code Playgroud)
看文档
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'
Run Code Online (Sandbox Code Playgroud)
然后,正如在文档中所见,可以访问对象的属性:
"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'
Run Code Online (Sandbox Code Playgroud)
还有很多,但您可以在文档中找到所有内容,这非常清楚。
| 归档时间: |
|
| 查看次数: |
4657 次 |
| 最近记录: |