python单元格内换行_如何在Python表中有多行单元格?

这里有一个你想做什么的类: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 | | |

| |

希望这有帮助。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值