如何在Python中打印文件时对齐列

时间:2016-02-12 17:18:27

标签: python list for-loop

我正在尝试以这种格式在文件中打印包含两个元素的列表:

A:               B
A:               B

这是我的代码

file=open("tmp.txt",w)
for i in range(len(List)):
     file.write(List[i][0].ljust(30, ' ')+List[i][1]+'\n')

问题是,如果包含很多单词,它会弄乱缩进 例如:

A:                   B
B
B

我希望我的输出看起来像这样:

A:                   B
                     B
                     B

2 个答案:

答案 0 :(得分:2)

您可以使用格式(https://docs.python.org/3/library/string.html#string-formatting)根据自己的喜好格式化字符串:

>>> List = [['A', 'B'], ['A134563421', 'B'], ['A', 'B']]
>>> for row in List:
   ... print '{0:30}{1}'.format(row[0], row[1])
   ... file.write('{0:30}{1}\n'.format(row[0], row[1]))

A                             B
A134563421                    B
A                             B

答案 1 :(得分:1)

您可以简单地执行以下操作,希望这是您想要的 实现。

import textwrap

List = [
    ["A1", "Some text that you want to write to a file, aligned in\n a column."],
    ["A2", "And this is a shorter text."]]

indention = 30
max_line_length = 30

file=open("tmp.txt", 'w')
for i in range(len(List)):

    out = List[i][0].ljust(indention, ' ')
    cur_indent = 0
    for line in List[i][1].split('\n'):
        for short_line in textwrap.wrap(line, max_line_length):
            out += ' '* cur_indent + short_line.lstrip() + "\n"
            cur_indent = indention

    file.write(out)

输出:

A1                            Some text that you want to
                              write to a file, aligned in
                              a column.
A2                            And this is a shorter text.