Python center string using format specifier

user1259332 picture user1259332 · Nov 14, 2012 · Viewed 31.4k times · Source

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?

Answer

ecatmur picture ecatmur · Nov 14, 2012

You need to centre each line separately:

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