【发布时间】: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)
但这似乎没有帮助。一个想法?谢谢!
【问题讨论】: