BaRud
BaRud

Reputation: 3218

output formatting with write in python

I am trying to write a code, which works fine, except the out.write is bit messed. The code that generates the output is:

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

which yeilds output looking like:

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

which is indeed correct, but messy. I am trying to write it in a left-adjusted column, like:

    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

How I can achieve this?

Upvotes: 0

Views: 120

Answers (2)

falsetru
falsetru

Reputation: 368974

Use 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  '

or 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  '

Upvotes: 3

poke
poke

Reputation: 387567

You can use str.ljust to justify text to a fixed length by adding whitespace:

>>> 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   

Upvotes: 1

Related Questions