Python String rjust()
Method
The rjust() method in Python is used to right-align a string by padding it with a specified character (default is a space).
Syntax
string.rjust(width, fillchar=' ')
Parameters:
width
– Total width of the resulting string (including original text + padding)fillchar
– (Optional) Character to use for padding (default is space)
Returns:
- A new string that is right-aligned and padded with the specified character on the left.
Example 1: Right-justify with spaces (default)
text = "Python"
print(text.rjust(10))
Python
Example 2: Right-justify with a specific fill character
text = "42"
print(text.rjust(5, "0"))
00042
Use Case: Padding values for printing aligned output
items = ["Apple", "Banana", "Cherry"]
for item in items:
print(item.rjust(10))
Apple
Banana
Cherry
Common Mistakes
- Using a fill character longer than one character (will raise a
TypeError
) - Expecting the original string to change (remember, strings are immutable)
Interview Tip
Use rjust()
in formatting columns, table-like outputs, or aligning numbers for printing.
Summary
rjust()
right-aligns the string by padding on the left.- You can customize the padding character using the
fillchar
parameter. - It returns a new string — original string is not modified.
Practice Problem
Write a program that accepts a word and prints it right-aligned in a field of width 20 using '*'
as padding.
word = input("Enter a word: ")
print(word.rjust(20, '*'))