Take the 2-minute tour ×

I am processing a text file containing coordinates x,y,z

     1      128  1298039
123388        0        2


every line is delimited into 3 items using

words = line.split ()

After processing data I need to write coordinates back in another txt file so as items in each column are aligned right (as well as the input file). Every line is composed of the coordinates

line_new = word[0]  + '  ' + word[1]  + '  ' word[2].

Is there any manipulator like std::setw ( ) etc. in C++ allowing to set the width and alignment?

share|improve this question
I doubt many will answer when you haven't accepted a single answer yet. –  Morten Kristensen Nov 22 '11 at 22:05
What's wrong with people nowadays? docs.python.org/library/string.html#formatstrings –  BasicWolf Nov 22 '11 at 22:07
What is the relationship between the variables words and word? –  Mark Byers Nov 22 '11 at 22:15

3 Answers 3

up vote 34 down vote accepted

Try this approach using the newer str.format syntax:

line_new = '{:>12}  {:>12}  {:>12}'.format(word[0], word[1], word[2])

And here's how to do it using the old % syntax (useful for older versions of Python that don't support str.format):

line_new = '%12s  %12s  %12s' % (word[0], word[1], word[2])
share|improve this answer

You can align it like that:

print '{:>8} {:>8} {:>8}'.format(*words)

where > means "align to right" and 8 is the width for specific value.

And here is a proof:

>>> for line in [[1, 128, 1298039], [123388, 0, 2]]:

       1      128  1298039
  123388        0        2

Ps. *line means the line list will be unpacked, so .format(*line) works similarly to .format(line[0], line[1], line[2]) (assuming line is a list with only three elements).

share|improve this answer
+1 for the *line syntax –  fantabolous Jul 16 at 12:51

It can be achieved by using rjust:

line_new = word[0].rjust(10) + word[1].rjust(10) + word[2].rjust(10)
share|improve this answer

Your Answer


