Python 文本在字符串模板中换行

Python text wrapping within a string template

我想在模板中打印不同长度的字符串,如下所示:

printTemplate = "{0:<5}|{1:<55}|{2:<20}"
print printTemplate.format("ID", "Text", "Category")
    for (docId, text, category) in textList:
        print printTemplate.format(docId, text, category)

结果是,

ID   |Text                                                   |Category
1500 |Monet is the French painter I have liked the best      |Painting
...

问题是文本字符串有时超过 55 个字符,这会破坏格式。我试过使用 TextWrapper,

from textwrap import TextWrapper
wrapper = TextWrapper(width=55)
...
        print printTemplate.format(docId, wrapper.fill(text), category)

但这似乎没有帮助。一个想法?谢谢!

您可以使用 PrettyTable,它会自动将输出格式化为列。

from prettytable import PrettyTable

x = PrettyTable(["ID", "Text", "Category"])
for (docId, text, category) in textList:
    x.add_row([docId, text, category])
print x

您需要按如下方式组合截断和填充:

printTemplate = "{0:<5}|{1:55.55}|{2:<20}"

This post 通过示例解释各种格式化程序可能会有很大帮助。