好吧,这看起来是一个非常基本的问题,但我在任何地方都找不到可行的答案,所以这里。
我有一些文字:
text = '''
Come and see the violence inherent in the system. Help! Help! I'm being
repressed! Listen, strange women lyin' in ponds distributin' swords is no
basis for a system of government. Supreme executive power derives from a
mandate from the masses, not from some farcical aquatic ceremony. The Lady
of the Lake, her arm clad in the purest shimmering samite held aloft
Excalibur from the bosom of the water, signifying by divine providence that
I, Arthur, was to carry Excalibur. THAT is why I am your king.'''
它不包含任何换行符或其他格式。
我想包装我的文本,以便在我运行代码时它在我的ipython输出窗口中正确显示。我还希望它居中,并且比整个窗口宽度(80个字符)短一点
如果我有一个短文本字符串(短于行长度),我可以简单地计算字符串的长度,并用空格将其填充到中心,或者使用
text.center()
属性正确显示它。如果我有一个只想包装的文本字符串,我可以使用:
from textwrap import fill
print(fill(text, width=50))
设置宽度为
所以我想我可以简单地:
from textwrap import fill
wrapped_text = (fill(text, width=50))
print(wrapped_text.center(80))
但没用。一切都是合理的。
我肯定我不是唯一一个尝试过的人。有人能帮我吗?
最佳答案
问题是center
需要单行字符串,fill
返回多行字符串。
答案是在连接每一行之前。
如果您查看center
的文档,它是:
"\n".join(wrap(text, ...))
所以,你可以跳过速记直接使用
fill
。例如,您可以编写自己的函数来完成您想要的任务:def center_wrap(text, cwidth=80, **kw):
lines = textwrap.wrap(text, **kw)
return "\n".join(line.center(cwidth) for line in lines)
print(center_wrap(text, cwidth=80, width=50))
虽然如果您只是在一个地方执行此操作,要立即将其打印出来,甚至不费心使用它可能更简单:
for line in textwrap.wrap(text, width=50):
print(line.center(80))