【发布时间】:2018-10-21 05:07:57
【问题描述】:
好的,所以这似乎是一个非常基本的问题,但我在任何地方都找不到可行的答案,所以就这样吧。
我有一些文字:
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))
但它不起作用。一切仍然是合理的。
我敢肯定,我不是唯一一个尝试这样做的人。谁能帮帮我?
【问题讨论】:
标签: python python-3.x text output string-formatting