使用格式说明符的python中心字符串

use*_*332 22 python formatting string-formatting python-3.x python-3.2

我有一个名为Message的字符串.

Message = "Hello, welcome!\nThis is some text that should be centered!"
Run Code Online (Sandbox Code Playgroud)

是的,这只是一个测试声明......

我试图将它作为一个默认的终端窗口,即宽度为80,并使用以下语句:

print('{:^80}'.format(Message))
Run Code Online (Sandbox Code Playgroud)

哪个印刷品:

           Hello, welcome!
This is some text that should be centered!           
Run Code Online (Sandbox Code Playgroud)

我期待的是:

                                Hello, welcome!                                 
                   This is some text that should be centered!                   
Run Code Online (Sandbox Code Playgroud)

有什么建议?

eca*_*mur 21

您需要分别居中每一行:

'\n'.join('{:^80}'.format(s) for s in Message.split('\n'))
Run Code Online (Sandbox Code Playgroud)