使用python中的write输出格式

时间:2014-05-13 14:58:09

标签: python python-3.x formatting

我正在尝试编写一个可以正常工作的代码,除了out.write有点乱。 生成输出的代码是:

with open('4fit', 'a') as outfile:
    outfile.write(' '.join(str(val) for val in popt))
    outfile.write("  "+str(ydata[0]))
    outfile.write("\n")

其中yeilds输出看起来像:

0.0001555 0.00319828 -0.040631943 -0.002219473  0.03331113
0.001402 0.00341955 -0.00602367 -0.002324949  0.31303529
0.002841 0.003655 -0.0010074 -0.001949339  0.67163649
0.003250 0.00383539 -0.000569682 -0.001761577  0.8000908

这确实是正确的,但很混乱。我试图在左侧调整的列中编写它,例如:

    0.0001555 0.00319828 -0.040631943 -0.002219473  0.03331113
    0.001402  0.00341955 -0.00602367  -0.002324949  0.31303529
    0.002841  0.003655   -0.0010074   -0.001949339  0.67163649
    0.003250  0.00383539 -0.000569682 -0.001761577  0.8000908

我怎么能做到这一点?

2 个答案:

答案 0 :(得分:3)

使用str.format

>>> data = 0.0001555,0.00319828,-0.040631943,-0.002219473,0.03331113
>>> '{:>12} {:>12} {:>12} {:>12} {:>12}'.format(*data)
'   0.0001555   0.00319828 -0.040631943 -0.002219473   0.03331113'
>>> '{:<12} {:<12} {:<12} {:<12} {:<12}'.format(*data)
'0.0001555    0.00319828   -0.040631943 -0.002219473 0.03331113  '

printf-style formatting

>>> '%12s %12s %12s %12s %12s' % tuple(data)
'   0.0001555   0.00319828 -0.040631943 -0.002219473   0.03331113'
>>> '%-12s %-12s %-12s %-12s %-12s' % tuple(data)
'0.0001555    0.00319828   -0.040631943 -0.002219473 0.03331113  '

答案 1 :(得分:1)

您可以使用str.ljust通过添加空格来将文本对齐到固定长度:

>>> lst = [[0.0001555, 0.00319828, -0.040631943, -0.002219473, 0.03331113], [0.001402, 0.00341955, -0.00602367, -0.002324949, 0.31303529], [0.002841, 0.003655, -0.0010074, -0.001949339, 0.67163649], [0.003250, 0.00383539, -0.000569682, -0.001761577, 0.8000908]]
>>> for line in lst:
    print(' '.join(str(val).ljust(12) for val in line))

0.0001555    0.00319828   -0.040631943 -0.002219473 0.03331113  
0.001402     0.00341955   -0.00602367  -0.002324949 0.31303529  
0.002841     0.003655     -0.0010074   -0.001949339 0.67163649  
0.00325      0.00383539   -0.000569682 -0.001761577 0.8000908