Python String rjust() Method
The rjust() method in Python is a string method used to right-align a string within a specified width by padding it with a specified character (default is a space). This method is helpful when you want to align text or numbers for formatting purposes.
s = 'geeks'
res = s.rjust(10)
print(res)
Output
geeks
Explanation:
- Original string "Hello" has a length of 5.
- Width is specified as 10, so 5 spaces are added to the left to make the total length 10.
Python String rjust() Method Syntax
Syntax: string.rjust(length, fillchar)
Parameters:
- length: length of the modified string. If length is less than or equal to the length of the original string then original string is returned.
- fillchar: (optional) characters which needs to be padded. If it’s not provided, space is taken as a default argument.
Return: Returns a new string of given length after substituting a given character in left side of original string.
Example 1: Using a Custom Padding Character
In this example, original string "Python" has a length of 6 and width is specified as 12, so 6 '-' characters are added to the left to make the total length 12.
# example string
string = 'geeks'
length = 8
fillchar = '*'
print(string.rjust(length, fillchar))
Output:
***geeks
Example 2: Width Less Than String Length
In this example, specified width (3) is less than the length of the string (5), so the original string is returned without any padding.
s = "World"
res = s.rjust(3)
print(res)
Output
World
Example 3: Aligning Numbers
In the below example, each number is right-aligned within a width of 5. The fillchar is specified as '0', so zeros are added to the left to fill the space.
n = ["10", "200", "3"]
for i in n:
print(i.rjust(5, '0'))
Output
00010 00200 00003