格式化输出字符串,右对齐 [英] Format output string, right alignment
问题描述
我正在处理一个包含坐标x,y,z的文本文件
I am processing a text file containing coordinates x, y, z
1 128 1298039
123388 0 2
....
每行都使用
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 = words[0] + ' ' + words[1] + ' ' words[2].
是否有任何操纵器,例如 std :: setw()
等在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])
这是使用%
旧语法(对于不支持 str.format
的Python旧版本很有用):
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])
这篇关于格式化输出字符串,右对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!