【问题标题】:Python text wrapping within a string template字符串模板中的 Python 文本换行
【发布时间】:2016-02-18 03:11:09
【问题描述】:

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

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)

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

【问题讨论】:

    标签: python string word-wrap


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2023-04-01
        • 2014-09-10
        • 2018-03-04
        • 1970-01-01
        • 1970-01-01
        • 2018-03-04
        • 2012-11-01
        • 2016-10-26
        • 1970-01-01
        相关资源
        最近更新 更多