Python String rjust()

Python String rjust() is used to right align the given string in specified space (length) and optionally fill the left out space with the specified character.

In this tutorial, we will learn the syntax and examples for rjust() method of String class.

Syntax

The syntax to call rjust() method on string x in Python is

x.rjust(length, character)

where

ParameterRequired / OptionalDescription
lengthRequiredAn integer representing the length of resulting string.
characterOptionalA character to fill the missing space. Default value is a single space character.
ADVERTISEMENT

Examples

In the following program, we take a string, and right align the string in a space of 20, and fill the left out space with '-' character.

Example.py

x = 'hello world'
result = x.rjust(20, '-')
print('Original String : ', x)
print('Result String   : ', result)
Try Online

Output

Original String :  hello world
Result String   :  ---------hello world

If character parameter is not specified, single space characters are filled in the left out space.

Example.py

x = 'hello world'
result = x.rjust(20)
print('Original String : ', x)
print('Result String   : ', result)
Try Online

Output

Original String :  hello world
Result String   :           hello world

Conclusion

In this Python Tutorial, we learned how to right align a string using rjust() method, with examples.