Coders Packet

String alignment in Python using ljust(), rjust() and center()

By Tanay R Dandekar

In this article, we are going to explore ljust, rjust and center methods in Python to align a given string just like we do in Microsoft word to left, right, or center align a given selected text.

1. ljust():

Using ljust() function, we can left-align a given text in a specified length of the string. Also, we can substitute the remaining space of string to a character.

Syntax:

left_str = text.ljust(length,fillchar)

where,

left_str: left-aligned string

text: given string

length: length of desired left-aligned string

fillchar: character to be filled in remaining space

Code:

#Python script for left alignment in string
text = "I LOVE CODING"
length = 40

#modified_str string will contain left-aligned given text and remaining space will be filled with '-'
modified_str = text.ljust(40,'-')
print(modified_str)

Output:

I LOVE CODING---------------------------

 

2. rjust():

Using rjust() function, we can right-align a given text in a specified length of the string. Also, we can substitute the remaining space of string to a character.

Syntax:

right_str = text.rjust(length,fillchar)

where,

right_str: right-aligned string

text: given string

length: length of desired left-aligned string

fillchar: character to be filled in remaining space

Code:

#Python script for right alignment in string 
text = "I LOVE CODING" 
length = 40 
#modified_str string will contain right-aligned given text and remaining space will be filled with '$' 
modified_str = text.rjust(40,'$') 
print(modified_str)

Output:

$$$$$$$$$$$$$$$$$$$$$$$$$$$I LOVE CODING

 

3. center():

Using center() function, we can center-align a given text in a specified length of the string. Also, we can substitute the remaining space of string to a character.

Syntax:

center_str = text.rjust(length,fillchar)

where,

center_str: center-aligned string

text: given string

length: length of desired left-aligned string

fillchar: character to be filled in remaining space

Code:

#Python script for center alignment in string
text = "I LOVE CODING"
length = 40
#modified_str string will contain center-aligned given text and remaining space will be filled with '0'
modified_str = text.center(40,'0')
print(modified_str)

Output:

0000000000000I LOVE CODING00000000000000

 

Thank you

Download project

Reviews Report

Submitted by Tanay R Dandekar (TanayRD1904)

Download packets of source code on Coders Packet