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

时间:2012-11-14 16:44:19

标签: python python-3.x formatting string-formatting python-3.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!                   

有什么建议吗?

2 个答案:

答案 0 :(得分:20)

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

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

答案 1 :(得分:0)

这是一种替代方案,可根据最长宽度自动居中。

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>