In this tutorial, we are going to learn about rjust() and ljust methods of strings. Let's see one one.
rjust(length, [fillchar])
The method rjust() will return a new string after adding the fillchar at the beginning of the based on the length. The argument length is required whereas fillchar is not.
By default, the fillchar is a space. Let's see an example.
Example
# initialzing a string string = 'tutorialspoint' # rjust -> 25 print(string.rjust(25))
Output
If you run the above code, then you will get the following result.
tutorialspoint
We can give the fillchar as well. And it needs to be a single character and not a string. Let's an example.
Example
# initialzing a string string = 'tutorialspoint' # rjust -> 25 print(string.rjust(25, '#'))
Output
If you run the above code, then you will get the following result.
###########tutorialspoint
If we provide a string in-place of character, then we will get an error. Let's see an example.
Example
# initialzing a string string = 'tutorialspoint' # rjust -> 25 print(string.rjust(25, '###'))
Output
If you run the above code, then you will get the following result.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-7-c5d59f29d30d> in <module> 3 4 # rjust -> 25 ----> 5 print(string.rjust(25, '###')) TypeError: The fill character must be exactly one character long
ljust(length, [fillchar])
The method ljust() is opposite to the rjust() method.
The method ljust() will return a new string after adding the fillchar at the end of the string on the length. The argument length is required whereas fillchar is not.
By default, the fillchar is a space. Let's see an example.
Example
# initialzing a string string = 'tutorialspoint' # rjust -> 25 print(string.ljust(25))
Output
If you run the above code, then you will get the following result.
tutorialspoint
We can give the fillchar as well. And it needs to be a single character and not a string. Let's an example.
Example
# initialzing a string string = 'tutorialspoint' # rjust -> 25 print(string.ljust(25, '#')) tutorialspoint###########
Output
If you run the above code, then you will get the following result.
tutorialspoint###########
If we provide a string in-place of character, then we will get an error. Let's see an example.
Example
# initialzing a string string = 'tutorialspoint' # rjust -> 25 print(string.ljust(25, '###'))
Output
If you run the above code, then you will get the following result.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-11-76fae427cc6f> in <module> 3 4 # rjust -> 25 ----> 5 print(string.ljust(25, '###')) TypeError: The fill character must be exactly one character long
Conclusion
If you have any doubts in the tutorial, mention them in the comment section.