pythonalignmentstring-formatting

Format output string, right alignment


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 = words[0]  + '  ' + words[1]  + '  ' words[2].

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


Solution

  • Try this approach using the newer str.format syntax. This uses a width of 12, space padded, right aligned.

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

    Example with the interpreter:

    >>> line = "123 456 789"
    >>> words = line.split(' ')
    >>> line_new = '{:>12}  {:>12}  {:>12}'.format(words[0], words[1], words[2])
    >>> print(line_new)
             123           456           789
    

    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' % (words[0], words[1], words[2])