Python String rjust() Method

The rjust() method returns a right-justified version of the original string, padded with a specified character (default is space) to reach a specified width.

Syntax

string.rjust(width, fillchar)

Parameters

width (required): The total length of the returned string after padding.

fillchar (Optional): The character used for padding (default is space).

Return Value

Returns a new string that is right-justified with the specified fill character, padding it to the left.

Examples

Right Justify a String

text = "mango"
result = text.rjust(10)
print(f"{result} is awesome")

Output:

     mango is awesome

In this example, "mango" has 5 character. Therefore, text.rjust(10) pads it with 5 spaces to the left, so it becomes:

     mango

Using a Custom Fill Character

text = "mango"
result = text.rjust(10, "-")
print(result) # Output: -----mango

When Width is Less Than String Length

If the specified width is less than or equal to the length of the original string, the original string is returned without any changes.

text = "mango"
result = text.rjust(3, "-")
print(result) # Output: mango

If you need to left-justify a string, you can use the ljust() method.