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

标签 python string word-wrap

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

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

关于字符串模板中的 Python 文本换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35472109/

相关文章:

python - Sphinx 描述 api 的有效输入值

python - 对 Pandas 数据集执行 SQL 查询

不使用 sprintf 将无符号整数转换为十六进制字符串

C# 字符串长度返回错误的数量

html - css word wrap 在不破坏它们的情况下包装整个单词?

html - 如何对齐两个 div(一个固定,另一个带有 break word 属性)?

python - Python 中的嵌套 WHILE 循环

javascript - 根据最大字符长度拆分字符串,但要考虑单词

html - 在绝对定位的容器内保留正常的自动换行

python - 字体和颜色语法错误