Implement Python String Alignment with String ljust(), rjust(), center() Function – Python Tutorial

By | August 30, 2019

Python string alignment contains: left align, right align and center align, which are very useful when printing string. In this tutorial, we will introduce you how to align a python string.

python string alignment

Syntax of ljust(), rjust() and center()

ljust( len, fillchr )
rjust( len, fillchr )
center( len, fillchr )

Parameters

len : The width of string to expand it.
fillchr (optional) : The character to fill in remaining space.

Functionality

ljust(): align python string left, such as #####string

rjust(): align python string right: such as string#####

center(): align python string center: such as ###string##

Here is an example:

str = 'www.tutorialexample.com'

ls = str.ljust(25, '#')
print('left string = ' + ls)

rs = str.rjust(25, '#')
print('right string = ' + rs)

cs = str.center(25, '#')
print('center string = ' + cs)

The string alignment result is:

left string = www.tutorialexample.com##
right string = ##www.tutorialexample.com
center string = #www.tutorialexample.com#

Notice: when length of python string is longer than len in ljust(), rjust() and center(), these three functions do not work.

To align python string, we also can use format() function to do. Here is a tutorial.

Best Practice to Pad Python String up to Specific Length – Python Tutorial

Leave a Reply

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