28

我有一个名为message.

message = "Hello, welcome!\nThis is some text that should be centered!"

我正在尝试使用以下语句将其置于默认终端窗口的中心,即 80 宽度:

print('{:^80}'.format(message))

哪个打印:

           Hello, welcome!
This is some text that should be centered!           

我期待类似的东西:

                                Hello, welcome!                                 
                   This is some text that should be centered!                   

有什么建议么?

4

2 回答 2

30

您需要将每条线分别居中:

'\n'.join('{:^80}'.format(s) for s in message.split('\n'))
于 2012-11-14T17:00:21.470 回答
1

这是一个替代方案,它将根据最长宽度自动居中您的文本。

def centerify(text, width=-1):
  lines = text.split('\n')
  width = max(map(len, lines)) if width == -1 else width
  return '\n'.join(line.center(width) for line in lines)

print(centerify("Hello, welcome!\nThis is some text that should be centered!"))
print(centerify("Hello, welcome!\nThis is some text that should be centered!", 80))

<script src="//repl.it/embed/IUUa/4.js"></script>

于 2017-05-27T13:45:56.873 回答