Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 351
user1259332 Avatar asked Nov 14 '12 16:11

user1259332


2 Answers

You need to centre each line separately:

'\n'.join('{:^80}'.format(s) for s in message.split('\n')) 
like image 111
ecatmur Avatar answered Oct 10 '22 21:10

ecatmur


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>
like image 25
EyuelDK Avatar answered Oct 10 '22 23:10

EyuelDK