我有一个列格式问题:
from math import sqrt
n = raw_input("Example Number? ")
n = float(n)
sqaureRootOfN = sqrt(n)
print '-'*50
print ' # of Decimals', '\t', 'New Root', '\t', 'Percent error'
print '-'*50
for a in range(0,10):
preRoot = float(int(sqaureRootOfN * 10**a))
newRoot = preRoot/10**a
percentError = (n - newRoot**2)/n*100
print ' ', a, '\t\t', newRoot, '\t\t', percentError, '%'
结果是:
不在同一列!?!
@Bjorn使用String.format规范给出了正确的答案。Python的字符串格式化程序有非常强大的方法来正确地对齐事物。下面是一个例子:
注意,我使用空格来分隔东西,而不是制表符。这是因为制表符实际上不是您想在这里使用的,因为制表符的空间规则不一致(并且取决于您的终端/查看器设置)。
答案是这样的:
这就是标签的工作原理。要获得正确的格式,应该使用^{} 。以你的例子来说,可能是这样的:
使用str.format
收益率
一些技巧/细节:
{p:13.9%}
的百分比符号允许您离开percentError
作为十进制数(不乘以100)并且 把%
放在最后。相关问题 更多 >
编程相关推荐