Python String rjust() Method

The rjust() method returns the right justified string with the specified width. If the specified width is more than the string length, then the string's remaining part is filled with the specified fill char. The default fill char is a space. The original string is returned if the width is less than the length of the given string.

Syntax:

str.rjust(width, fillchar)

Parameters:

  1. width : (Required) The length of the right justified string.
  2. fillchar : (Optional) character to fill the remaining space of the right justified string if the width is more than its length.

Return Value:

Returns a right justified string.

The following example demonstrates the rjust() method.

Example: rjust()
>>> mystr = 'Hi'
>>> mystr.rjust(4)
'  Hi'
>>> mystr.rjust(4, '-')
'--Hi'
>>> mystr.rjust(2, '-')
'Hi'

In the above example, mystr.rjust(4) creates a new string of length 4 and make 'Hi' right justified. A fillchar is not mentioned; therefore, the default value space is used. So, the result is 'Hi ' with 2 spaces on the right side. In the same way, mystr.rjust(4, '-') results in 'Hi--'. The total length of a new string is 4 and appends two '-' chars as a fillchar.

If the given width is the same or less than the original string, then the rjust() method does nothing and returns the original string, as shown below.

Example: rjust()
>>> mystr = 'Hello'
>>> mystr.rjust(2)
'Hello'
>>> mystr.rjust(2,'*')
'Hello'
>>> mystr.rjust(5,'*')
'Hello'

The fillchar parameter must be a single character. If given more than one chars as fillchar then it will throw a TypeError, as shown below.

Example: rjust()
>>> mystr = 'Hello World'
>>> mystr.rjust(20,'->')
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    'Hello World'.rjust(20,'->')
TypeError: The fill character must be exactly one character long
Want to check how much you know Python?