sie*_*sta 15 python printing string floating-point
我有点想用python编程,所以请放轻松我.我正在尝试调用字符串属性rjust并指定浮点的精度.这是代码和示例输出(注意0.00右边没有对齐):
print '%s: %s %s \tchange: %.2f' % (Instance1.symbol.ljust(5),
Instance1.name.ljust(50), Instance1.buyprices.rjust(10), Instance1.val)
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
AXP : American Express Company 55.38 change: -1.15
AXR : Amrep Corp. 6.540 change: 0.00
Run Code Online (Sandbox Code Playgroud)
Lev*_*von 25
这显示了如何使用旧%格式化方法使用两个小数点格式化输出的示例:
v1 = 55.39
v2 = -1.15
v3 = 6.54
v4 = 0.00
print '%8.2f %8.2f' % (v1, v2)
print '%8.2f %8.2f' % (v3, v4)
Run Code Online (Sandbox Code Playgroud)
相应的输出:
55.39 -1.15
6.54 0.00
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用"新的和改进的" .format()函数,它将会存在一段时间,值得了解.以下将生成与上面相同的输出:
print '{:8.2f} {:8.2f}'.format(v1, v2)
print '{:8.2f} {:8.2f}'.format(v3, v4)
Run Code Online (Sandbox Code Playgroud)
两组格式化指令为您的数字分配8个空格,将其格式化为小数点后2位数的浮点数.您必须调整这些值以满足您的需求.
我认为使用这种方法来格式化输出会更容易,因为它.format()会让你对输出有很多控制(包括校对,填充,精度).