Center-aligning text on console in Python Center-aligning text on console in Python shell shell

Center-aligning text on console in Python


You can use str.center

s = "hello world"s.center(40)>>> '              hello world               '


If you are using python version 3.6 (as I love to use it instead of 2.7) you can use the caret character in the format function:

>>> '{:^50}'.format('sample text')'                   sample text                    '     # with a length of 50.

If you want to fill the gap you use:

>>> '{:*^50}'.format('sample text')'*******************sample text********************'     # * is the fill character.


import shutildef print_centre(s):    print(s.center(shutil.get_terminal_size().columns))