且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在python输出中居中多行文本

更新时间:2023-12-04 11:48:52

问题在于 center 需要单行字符串,而 fill 返回一个多行字符串.

The problem is that center expects a single-line string, and fill returns a multiline string.

答案是将每一行居中,然后再将它们连接起来.

The answer is to center each line, before joining them up.

如果您查看 fill 的文档,它的简写为:

If you look at the docs for fill, it's shorthand for:

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

因此,您可以跳过该速记并直接使用 wrap.例如,您可以编写自己的函数来满足您的需求:

So, you can just skip that shorthand and use wrap directly. For example, you can write your own function that does exactly what you want:

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))

虽然如果你只在一个地方这样做,为了立即打印出来,甚至不打扰加入它可能更简单:

Although if you're only doing this in one place, to immediately print it out, it's probably simpler to not even bother joining it:

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