Python String rjust()

The rjust() method right aligns the string up to a given width using a specified character.

Example


rjust() Syntax

The syntax of the rjust() method is:

string.rjust(width,[fillchar])

Here, rjust() right aligns string using fillchar up to width.


rjust() Parameters

The rjust() method can take two parameters:

  • width - width of the given string
  • fillchar(Optional) - character to fill the remaining space of the width

Note: If width is less than or equal to the length of the string, the original string is returned.


rjust() Return Value

The rjust() method returns:

  • the right-justified string with the given width.

Example 1: Python String rjust()

Output

 $$$$programming

In the above example, we have used the rjust() method to right justify the text string.

Here, text.rjust(15, '$') right justifies the text string i.e. 'programming' to width 15 using the specified fillchar '$'.

The method returns the string '$$$$programming' whose width is 15.


Example 2: rjust() with Default fillchar

Output

    cat

Here, we have not passed fillchar so the rjust method takes the default filling character which is whitespace.

Here text.rjust(7) returns ' cat' after right justifying the string 'cat' up to width 7 using space.


Example 3: rjust() With width Less Than or Equal to String

If width is less than or equal to the length of the string, the rjust() method returns the original string. For example,

Output

Ninja Turtles
Ninja Turtles

Here, we have passed width:

  • 13 - equal to the length of text
  • 10 - less than the length of text

In both of the cases, the rjust() method returns the original string 'Ninja Turtles'.


Recommended Reading: