使用格式说明蟒蛇中心串(python centre string using format spec

2019-07-03 19:33发布

我有一个名为消息字符串。

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!                   

有什么建议?

Answer 1:

您需要单独中心的每一行:

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


Answer 2:

这里是将汽车中心的基于文本的最长宽度的选择。

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>



文章来源: python centre string using format specifier