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.
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.
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
#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)
I LOVE CODING---------------------------
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.
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
#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)
$$$$$$$$$$$$$$$$$$$$$$$$$$$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.
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
#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)
0000000000000I LOVE CODING00000000000000
Thank you
Submitted by Tanay R Dandekar (TanayRD1904)
Download packets of source code on Coders Packet
Comments