在 python 输出中居中多行文本

Wil*_*ill 3 python text string-formatting python-3.x output

好吧,这似乎是一个非常基本的问题,但我在任何地方都找不到可行的答案,所以就在这里。

我有一些文字:

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.'''
Run Code Online (Sandbox Code Playgroud)

它不包含任何换行符或其他格式。我想换行文本,以便在运行代码时它可以在 ipython 输出窗口中正确显示。我还希望它居中,并且比整个窗口宽度(80 个字符)短一点

如果我有一个短文本字符串(比行长度短),我可以简单地计算字符串的长度并用空格填充它以使其居中,或者使用该text.center()属性来正确显示它。

如果我有一个只想换行的文本字符串,我可以使用:

from textwrap import fill
print(fill(text, width=50))
Run Code Online (Sandbox Code Playgroud)

并将宽度设置为任意值

所以我想我可以简单地:

from textwrap import fill
wrapped_text = (fill(text, width=50))
print(wrapped_text.center(80))
Run Code Online (Sandbox Code Playgroud)

但它不起作用。一切仍然合理。

我确信我不是唯一一个尝试这样做的人。有人可以帮我吗?

aba*_*ert 5

问题是center需要一个单行字符串,并fill返回一个多行字符串。

答案是center每一行,然后将它们连接起来。

如果您查看 的文档fill,它是以下内容的简写:

"\n".join(wrap(text, ...))
Run Code Online (Sandbox Code Playgroud)

因此,您可以跳过该简写并wrap直接使用。例如,您可以编写自己的函数来完全执行您想要的操作:

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))
Run Code Online (Sandbox Code Playgroud)

尽管如果您只在一个地方执行此操作,但要立即将其打印出来,则可能更简单,甚至不必费心join处理它:

for line in textwrap.wrap(text, width=50):
    print(line.center(80))
Run Code Online (Sandbox Code Playgroud)