rjust() makes a string at least width characters long by adding padding on the left, so the text stays at the right. "7".rjust(3) is " 7", which is two spaces plus the text.
The padding is made of spaces unless you pass a one-character fillchar. If the string is already as long as width, or longer, it is returned as it is: rjust() never cuts text. The method returns a new string.
text.rjust() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Pass the total width. The fill character is optional.
Returns '00-7'. The sign is treated as an ordinary character, which is why zfill() is better for numbers.
To pad on the right use ljust(), to centre the text use center(), and to pad a number with zeros and keep its sign use zfill().
Library declarations
python
str.rjust(width[, fillchar]) -> str
# returns: a new string at least width characters long
# raises: TypeError if fillchar is not exactly one character
Parameters
Parameter
Description
width
Required. The length of the final string. If it is not larger than the length of the text, nothing is added.
fillchar
Optional. The character used for padding. It must be a string of exactly one character. Default is a space.
Return Value
Return Value
Description
str
A new string of length max(width, len(text)), with the text at the right. The original string is not changed.
Python Examples
Example 1 — Right-Align Text in a Field
Pad a number to 6 characters with spaces and with stars, and try a width that is too small.
python
number = "42"
print(repr(number.rjust(6)))
print(number.rjust(6, "*"))
print(number.rjust(1))
print(len(number.rjust(6)))
Output
' 42'
****42
42
6
How It Works
Spaces on the left. The text has 2 characters, so 4 spaces are added before it to reach 6.
A fill character. The second argument replaces the spaces with stars.
A small width does nothing. The width 1 is smaller than the text, so 42 is returned unchanged.
The length is the width. The padded text has 6 characters.
Example 2 — Print a Column of Numbers
Right-align numbers so that the digits line up under each other.
python
totals = [5, 120, 3400]
for value in totals:
print(str(value).rjust(6))
Output
5
120
3400
How It Works
Convert first.str(value) turns each number into text, because rjust() is a string method.
The same width. Every line is 6 characters long.
The digits line up. The last digit of every number is in the same column, which is how people expect numbers to look.
Example 3 — The Minus Sign Trap
Compare rjust() with zfill() when the number is negative.