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

2024-04-24 06:52:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个包含坐标x,y,z的文本文件

     1      128  1298039
123388        0        2
....

每行使用

words = line.split()

处理完数据后,我需要将坐标写回另一个txt文件中,以便每列中的项都右对齐(以及输入文件)。每条线都是由坐标组成的

line_new = words[0]  + '  ' + words[1]  + '  ' words[2].
< > C++中是否有任何机械手,如^ {< CD1> },允许设置宽度和对齐?


Tags: 文件数据txtnew宽度linesplitwords
3条回答

使用较新的^{} syntax尝试此方法:

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

下面介绍如何使用旧的%语法(对于不支持str.format的旧版本Python很有用):

line_new = '%12s  %12s  %12s' % (word[0], word[1], word[2])

可以这样对齐:

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

其中,>表示“向右对齐”,而8是特定值的宽度

这里有一个证据:

>>> for line in [[1, 128, 1298039], [123388, 0, 2]]:
    print('{:>8} {:>8} {:>8}'.format(*line))


       1      128  1298039
  123388        0        2

Ps.*line意味着line列表将被解包,因此.format(*line)的工作方式与.format(line[0], line[1], line[2])类似(假设line是一个只有三个元素的列表)。

它可以通过使用rjust来实现:

line_new = word[0].rjust(10) + word[1].rjust(10) + word[2].rjust(10)

相关问题 更多 >