Python的:格式化输出字符串,右对齐字符串、右对齐、Python

2023-09-11 23:32:32 作者:欲罢不能.

我在处理含有x,y坐标的文本文件,Z

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

     1      128  1298039
123388        0        2

...

每行使用分隔成3项

words = line.split ()

处理数据我需要回另一个txt文件写坐标,以便在各列中的数据项都对准右(以及输入的文件)之后。每一行是由坐标

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

有没有类似标准)的任何操纵::运输及工务局局长(等在C ++中允许设置宽度和对齐方式?

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

推荐答案

使用试试这个方法较新的 str.format 语法:

Try this approach using the newer str.format syntax:

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

和这里是如何使用旧语法(旧版本的Python不支持 str.format ):

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