python centre string using format specifier

孤街醉人 提交于 2020-01-09 19:05:19

问题


I have a string called Message.

Message = "Hello, welcome!\nThis is some text that should be centered!"

Yeah, it's just a test statement...

And I'm trying to centre it for a default Terminal window, i.e. of 80 width, with this statement:

print('{:^80}'.format(Message))

Which prints:

           Hello, welcome!
This is some text that should be centered!           

I'm expecting something like:

                                Hello, welcome!                                 
                   This is some text that should be centered!                   

Any suggestions?


回答1:


You need to centre each line separately:

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



回答2:


Here is an alternative that will auto center your text based on the longest width.

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>


来源:https://stackoverflow.com/questions/13383244/python-centre-string-using-format-specifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!