Python string API provides two utility function to create a new string of specified length from the source string with right and left justification.
Table of Contents
Python String rjust()
This function returns a new string of specified length with right-justified source string. We can specify the character to use for the padding, the default is whitespace. If the specified length is smaller than the source string, then the source string is returned.
Let’s look at some examples of rjust() function.
s = 'Hello'
s1 = s.rjust(20)
print(f'***{s1}***')
s1 = s.rjust(20, '#')
print(f'***{s1}***')
s1 = s.rjust(20, 'ç')
print(f'***{s1}***')
s1 = s.rjust(4)
print(f'***{s1}***')
Output:
*** Hello***
***###############Hello***
***çççççççççççççççHello***
***Hello***
Python String ljust()
Python string ljust() is very similar to the rjust() function. The only difference is that the original string is right-justified. Let’s have a look at some examples.
s = 'Hello'
s1 = s.ljust(20)
print(f'***{s1}***')
s1 = s.ljust(20, '#')
print(f'***{s1}***')
s1 = s.ljust(20, 'ç')
print(f'***{s1}***')
s1 = s.ljust(4)
print(f'***{s1}***')
Output:
***Hello ***
***Hello###############***
***Helloççççççççççççççç***
***Hello***
If you want center-aligned string then you can use Python String center() function.
Error Scenarios with rjust() and ljust() functions
Let’s see some error scenarios that may come when using rjust() and ljust() functions.
s.ljust('#')
s.rjust('#')
Error: TypeError: ‘str’ object cannot be interpreted as an integer
>>> s.ljust()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ljust() takes at least 1 argument (0 given)
>>>
>>> s.rjust()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: rjust() takes at least 1 argument (0 given)
>>>
>>> s.ljust(20, '#$')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long
>>>
>>> s.rjust(20, '#$')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long
>>>
Official Documentation: rjust(), ljust()