Justifying and aligning text in Python

If you need some alignment in the text you output from your program, than you can use the ‘ljust’, ‘rjust’ and ‘center’ string methods to accomplish that.

>>> greetings = 'Hello World!'
>>> greetings.rjust(30)
'                  Hello World!'
>>> greetings.ljust(30)
'Hello World!                  '
>>> greetings.center(30)
'         Hello World!         '

All the above methods accept a second parameter which allows you to fill the gap in the output with a character.

>>> greetings.center(30, '-')
'---------Hello World!---------'
>>> greetings.ljust(30, '-')
'Hello World!------------------'
>>> greetings.rjust(30, '-')
'------------------Hello World!'

Leave a Reply

Your email address will not be published. Required fields are marked *