Python String rjust() Function
The String rjust()
method returns right-justified string of length width
. Padding is done using the specified fillchar
(default value is an ASCII space).
The original string is returned as it is, if width
parameter is less than or equal to string length.
Syntax
my_string.rjust(width, fillchar)
rjust() Parameters
Python String rjust()
function parameters:
Parameter | Condition | Description |
---|---|---|
width | Required | The length of the string |
fillchar | Optional | A character you want to use as a fill character. Default value is an ASCII space. |
If fillchar
is not provided, a whitespace is taken as the default argument.
rjust() Return Value
Python String rjust()
function returns a new string that is right-justified within a string of the specified length, using the specified fill character.
Examples
Example 1: Right-Justify a String using rjust() method
By default, the string is padded with whitespace (ASCII space,
).
my_str = 'Right'
result = my_str.rjust(10)
print(f"'{result}'") # Output: ' Right'
output
' Right'
Example 2: Right-Justify a String with Custom Padding
You can modify the padding character by specifying a fill character.
For example, right-justify a string with *
as a fill character
my_str = 'Right'
result = my_str.rjust(10, '*')
print(f"'{result}'") # Output: '*****Right'
outputs
'*****Right'
Example 3: Right-Justify a String with too small width
If the width is less than or equal to string length, then the original string is returned.
my_str = 'Right'
result = my_str.rjust(2, '*')
print(f"'{result}'") # Output: 'Right'
output
'Right'
Equivalent Method to Right-Justify a String
You can right-justify a string as you would do with rjust()
method by using format()
method.
For example, using the rjust()
method:
my_str = 'Right'
result = my_str.rjust(10, '*')
print(result) # Output: *****Right
output
*****Right
This is equivalent to the use of format()
method:
my_str = 'Right'
result = '{:*>10}'.format(my_str)
print(result) # Output: *****Right
output
*****Right