Python 3 – String rjust() Method
The rjust()
method is a string method that is used to pad a string with a given character until the desired length is achieved. The method is used to justify a string to the right-hand side.
Syntax
The syntax for the rjust()
method is as shown below:
string.rjust(width[, fillchar])
The rjust()
method takes two arguments; width
and fillchar
.
The width
argument specifies the width of the output string. If the string is shorter than the specified width, it is padded with the fillchar
argument.
The fillchar
argument is optional, and if not provided, the rjust()
method pads the string with whitespace.
Return Value
The rjust()
method returns a string that is left-justified with the specified width.
Examples of Using the rjust() Method
Example 1
In this example, the rjust()
method is used to justify a string to the right-hand side, with a specified width of 10
. Since we did not provide the fillchar
argument, whitespace is used to fill the space between the string and the width.
# Using rjust() method to justify a string to the right
string = "Python"
res = string.rjust(10)
print(res)
Output
Python
Example 2
In this example, the rjust()
method is used to justify a string to the right-hand side, with a specified width of 10
, but this time we provided the fillchar
argument.
# Using rjust() method to justify a string to the right, with a fill character
string = "Python"
res = string.rjust(10, "*")
print(res)
Output
****Python
The output shows that the string has been padded with the *
character.
Example 3
In this example, the rjust()
method is used to justify a string to the right-hand side, with a specified width of 10
, but this time the width is less than the length of the string.
# Using rjust() method to justify a string to the right, where the width is less than the length of the string
string = "Python"
res = string.rjust(4)
print(res)
Output
Python
Since the specified width is less than the length of the string, the rjust()
method did not add any padding to the string.
Conclusion
The rjust()
method is a useful string method that can be used to pad a string on the right with a given character until the desired width is achieved. It is useful when working with text that needs to be aligned or formatted in a specific way. Always remember to provide the width argument, and optionally you can provide the fill character argument to specify which character to use for padding.