Python string rjust() and ljust() methods
Hello coders. Welcome to this post where we will learn Python string rjust() and ljust() methods.
We are well-known with justify icons in Ms-word which align the text to right, left and center. The same concept is for Python where we use rjust() method for the alignment of text to right and ljust() for left alignment of text.
Also read: Multiline string in Python
Let’s begin learning with examples:
rjust() and ljust() methods in Python
rjust() method
In Python, we use rjust() method for the alignment of string to right.
Synatx: rjust() in Python
rjust(length, fillCharacter)
where length is the width of expansion of string and fillcharacter is the character which we want to fill at the place of blank spaces.
string="Life is a gift of god" #Before right alignment print(string) #After using rjust() print(string.rjust(30,"#"))
Output:
Life is a gift of god #########Life is a gift of god
ljust() method
For the alignment of strings to left ljust() is used in Python.
Syntax: ljust in Python
ljust(length, fillCharacter)
where length is the width of expansion of string and fillcharacter is the character which we want to fill at the place of blank spaces.
string="Life is a gift of god" #Before left alignment print(string) #After using ljust() print(string.ljust(30,"*"))
Output:
Life is a gift of god Life is a gift of god*********
Note: Providing fillcharcater is not necessary. If you don’t provide any fill character blank space is automatically used.
I hope you have understood the concept of Python string rjust() and ljust() methods. If you find anything incorrect please comment below. If you want post on any other topics of Python, comment topic name below.
Also read: How to implement list as a stack in Python
Leave a Reply