我有一个名为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!
有什么建议吗?
您需要将每行分别居中:
'\n'.join('{:^80}'.format(s) for s in message.split('\n'))
这里是一种选择,它将根据最长的宽度自动居中文本。
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>