Python String rjust()

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

Example

text = 'Python'

# right aligns 'Python' up to width 10 using '*' result = text.rjust(10, '*')
print(result) # Output: ***Python

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

text = 'programming'

# right aligns text up to length 15 using '$' result = text.rjust(15, '$')
print(result)

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

text = 'cat'

# passing only width and not specifying fillchar result = text.rjust(7)
print(result)

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,

text = 'Ninja Turtles'

# width equal to length of string result1 = text.rjust(13, '*')
print(result1)
# width less than length of string result2 = text.rjust(10, '*')
print(result2)

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'.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges