在python outpu中居中多行文本

2024-04-29 09:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有一些短信:

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()属性来正确显示它。在

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

^{pr2}$

把宽度设为任意值

所以我想我可以简单地:

from textwrap import fill
wrapped_text = (fill(text, width=50))
print(wrapped_text.center(80))

但它不起作用。一切都是合理的。在

我肯定我不是唯一一个试图这么做的人。有人能帮我吗?在


Tags: ofthe字符串textinfrom文本宽度
2条回答

问题是center需要一个单行字符串,^{}返回一个多行字符串。在

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

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

"\n".join(wrap(text, ...))

所以,您可以跳过速记直接使用wrap。例如,您可以编写自己的函数来执行您想要的:

^{pr2}$

虽然如果只在一个地方执行此操作,要立即将其打印出来,可能更简单的做法是不必麻烦join打印它:

for line in textwrap.wrap(text, width=50):
    print(line.center(80))

wrapped_text是一个字符串列表,因此循环遍历字符串并使其居中。在

import textwrap

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."    

wrapped_text = textwrap.wrap(text)
for line in wrapped_text:
    print(line.center(80))

相关问题 更多 >