Python中心字符串使用格式说明符

问题描述 投票:23回答: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个回答
22
投票

您需要将每行分别居中:

'\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.