The Python rjust() function allows us to right justify string variables.

string = "hello"

print(string.rjust(8))

#Output:
   hello

You can also pass a second parameter which will be used to fill the blank spaces created by rjust().

string = "hello"

print(string.rjust(8, "x"))

#Output:
xxxhello

When working with strings, the ability to easily modify the values of the variables easily is valuable.

One such situation where you might want to make a change to a string is if you want to right justify a string variable.

The Python rjust() function allows us to right justify string variables.

rjust() takes two parameters. The first is the length of the new string that rjust() will create and the second parameter is a fill character to add to the left of the string.

Below is a simple example showing you how to use rjust() to return a right justified string in Python.

string = "hello"

print(string.rjust(8))

#Output:
   hello

Using the Fill Parameter with rjust() Function

The second parameter allows you to fill the blank space with a given character. This can be useful if you want to add leading characters to a string.

Below is a simple example showing you how to return a right justified string with rjust() and fill the blank spaces with a character in Python.

string = "hello"

print(string.rjust(8, "x"))

#Output:
xxxhello

Using rjust() Function to Add Leading Zeros to String in Python

One useful example of rjust() is that you can add leading zeros to a string in Python is with the rjust() function.

Adding leading zeros with rjust() is useful if you want to get a specific length for your new string and don’t always know the length of the string variable you are using.

Also, it’s possible you are working with data which has an ID or a record number which is represented with a number and you need to add leading zeros to maintain data integrity.

Below is an example of adding leading zeros to a string with rjust() in Python.

string = "hello"

print(string.rjust(8,"0"))

#Output:
000hello

Left Justifying String Variable with Python ljust() Function

Instead of right justifying a string, if you want to left justify a string, you can use the Python ljust() function.

Just like rjust(), ljust() takes two parameters. The first is the length of the new string that ljust() will create and the second parameter is the character to add to the right of the string.

Below is a simple example showing you how to use rjust() in Python.

string = "hello"

print(string.ljust(8, "x"))

#Output:
helloxxx

Hopefully this article has been useful for you to learn how to use the Python rjust() function.

Categorized in:

Python,

Last Update: March 11, 2024