How to use rjust() method in python to right justified a string

rjust() method of python string with example:

rsjust method is used to create right justified string in Python. We can give one width and fill character, it will create one right justified string and return back that string.

In this post, I will show you how to use rjust with examples.

rjust() definition:

rjust is defined as below:

rjust(length[,character])

Here, length is the width of the string that we need and character is the fill character. If it is less than or equal to the length of the given string, it returns that string.

character is optional. It uses blanks if we don’t use character.

Example of rjust:

Example of rjust to right justify a string without fill character:

Let’s take a look at the example below:

given_string = 'one'

print(given_string.rjust(2))
print(given_string.rjust(4))
print(given_string.rjust(5))
print(given_string.rjust(6))

If you run this program, it will print:

python right justify using rjust

  • The first one is not adding any space to left because 2 is smaller than the size of the given string.
  • 2nd one added one space to left and right justify the text. Similarly, 3rd and 4th statements added 2 and 3 blank spaces to the left.

Example of rjust to right justify a string with fill character:

Now, let’s try with fill characters with the above example:

given_string = 'one'

print(given_string.rjust(2,'*'))
print(given_string.rjust(4,'*'))
print(given_string.rjust(5,'*'))
print(given_string.rjust(6,'*'))

It will print:

python right justify with filled character

As you can see here, the blank spaces are replaced with ’*’, this can be any other character.

You might also like: