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

问题描述 投票:20回答:2

我有一个名为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!                   

有什么建议?

python python-3.x formatting string-formatting python-3.2
2个回答
21
投票

您需要分别居中每一行:

'\n'.join('{:^80}'.format(s) for s in Message.split('\n'))

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>
© www.soinside.com 2019 - 2024. All rights reserved.