如何组织此代码的输出?

时间:2013-08-10 03:47:53

标签: python python-2.7

这个程序的输出是一个表,但它有点乱。如何对齐不同的列?感谢

代码:

import math   

for a in range(1, 10):
    x = 3.0
    while True:
        y = (x + a/x) / 2
        if y == x:
            break
        x = y  
    sq = math.sqrt(a)
print float(a), sq, x, abs(sq - x)

1 个答案:

答案 0 :(得分:2)

使用str.format

import math   

for a in range(1, 10):
    x = 3.0
    while True:
        y = (x + a/x) / 2
        if y == x:
            break
        x = y  
    sq = math.sqrt(a)
    print '{:>5} {:>5.10f} {:>5.10f} {:>5.10f}'.format(float(a), sq, x, abs(sq - x))

打印

  1.0 1.0000000000 1.0000000000 0.0000000000
  2.0 1.4142135624 1.4142135624 0.0000000000
  3.0 1.7320508076 1.7320508076 0.0000000000
  4.0 2.0000000000 2.0000000000 0.0000000000
  5.0 2.2360679775 2.2360679775 0.0000000000
  6.0 2.4494897428 2.4494897428 0.0000000000
  7.0 2.6457513111 2.6457513111 0.0000000000
  8.0 2.8284271247 2.8284271247 0.0000000000
  9.0 3.0000000000 3.0000000000 0.0000000000