这里有一个你想做什么的类:import textwrap
class Table:
def __init__(self,
contents,
wrap,
wrapAtWordEnd = True,
colDelim = "|",
rowDelim = "-"):
self.contents = contents
self.wrap = wrap
self.colDelim = colDelim
self.wrapAtWordEnd = wrapAtWordEnd
# Extra rowDelim characters where colDelim characters are
p = len(self.colDelim) * (len(self.contents[0]) - 1)
# Line gets too long for one concatenation
self.rowDelim = self.colDelim
self.rowDelim += rowDelim * (self.wrap * max([len(i) for i in self.contents]) + p)
self.rowDelim += self.colDelim + "\n"
def withoutTextWrap(self):
string = self.rowDelim
for row in self.contents:
maxWrap = (max([len(i) for i in row]) // self.wrap) + 1
for r in range(maxWrap):
string += self.colDelim
for column in row:
start = r * self.wrap
end = (r + 1) * self.wrap
string += column[start : end].ljust(self.wrap)
string += self.colDelim
string += "\n"
string += self.rowDelim
return string
def withTextWrap(self):
print(self.wrap)
string = self.rowDelim
# Restructure to get textwrap.wrap output for each cell
l = [[textwrap.wrap(col, self.wrap) for col in row] for row in self.contents]
for row in l:
for n in range(max([len(i) for i in row])):
string += self.colDelim
for col in row:
if n < len(col):
string += col[n].ljust(self.wrap)
else:
string += " " * self.wrap
string += self.colDelim
string += "\n"
string += self.rowDelim
return string
def __str__(self):
if self.wrapAtWordEnd:
return self.withTextWrap()
else:
return self.withoutTextWrap()
if __name__ == "__main__":
l = [["heading 1", "heading 2", "asdf"],
["some text", "some more text", "Lorem ipsum dolor sit amet."],
["lots and lots and lots and lots and lots of text", "some more text", "foo"]]
table = Table(l, 20, True)
print(table)
withTextWrap()使用您提到的textwrap模块,并使用其输出来构建表表示。在玩这个的时候,我还想出了一种方法来做你想做的事情(几乎),没有textwrap模块,你可以在withoutTextWrap()方法中看到。我之所以说“几乎”,是因为textwrap模块在单词末尾正确地换行,而我的方法在换行点直接断开字符串。在
因此,如果创建第三个构造函数参数设置为True的表,则使用textwrap模块,该模块生成以下输出:
^{pr2}$
如果该参数是False,则非textwrap版本称为:| |
|heading 1 |heading 2 |asdf |
| |
|some text |some more text |Lorem ipsum dolor si|
| | |t amet. |
| |
|lots and lots and lo|some more text |foo |
|ts and lots and lots| | |
| of text | | |
| |
希望这有帮助。在