String rjust() Method in Python

Python String rjust() Method

In Python, the rjust() method is a built-in string method used to right-justify a string within a specified width. It returns a new string padded with a given character (or whitespace by default) on the left side to reach the desired width.

The syntax of the rjust() method is as follows:

string.rjust(width, fillchar)

Here:

  • string: This is the original string that you want to right-justify.
  • width: It specifies the total width of the resulting string, including the original string and any padding characters.
  • fillchar (optional): This is the character used for padding. If not provided, it defaults to whitespace.

Let's see some examples to understand how the rjust() method works:

Using rjust() with default fill character (whitespace)

text = "Hello"
padded_text = text.rjust(10)
print(padded_text)  # Output: "     Hello"

In this example, the original string "Hello" is right-justified to a total width of 10 characters, including the text itself. Since the default fill character is whitespace, the string is padded with spaces on the left side to achieve the specified width.

Using rjust() with a custom fill character

text = "Hello"
padded_text = text.rjust(10, '*')
print(padded_text)  # Output: "*****Hello"

Here, we have specified the fill character as '', so the original string "Hello" is right-justified to a width of 10 characters by padding with asterisks () on the left side.

Using rjust() with a width smaller than the original string

text = "Hello"
padded_text = text.rjust(3)
print(padded_text)  # Output: "Hello"

If the specified width is smaller than the length of the original string, the rjust() method will not pad the string and will return the original string as it is.

The rjust() method is handy when you need to format text output, aligning strings to a specific width, or create well-formatted tables or columns in your programs.