Search code examples
pythonpython-3.xformattingstring-formattingpython-3.2

Python center string using format specifier


I have a string called message.

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

And I'm trying to center 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?


Solution

  • You need to centre each line separately:

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