Python String rjust() and ljust()

Filed Under: Python

Python string API provides two utility function to create a new string of specified length from the source string with right and left justification.

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 rjust()

If you are not familiar with f-prefixed string formatting, please read f-strings in Python.

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***

python string ljust()

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

Python string rjust() and ljust() TypeError


>>> 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
>>> 
You can checkout more Python examples from our GitHub Repository.

Official Documentation: rjust(), ljust()

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages