Python rjust

Python rjust method is used to Justify the string to the Right-hand side or trailing and fill the remaining width with the specified character. By default, the Python rjust function considers white spaces and returns the new string.

In this section, we discuss how to write Python rjust Function with an example, and is syntax is shown below.

String_Value.rjust(Width, Char)
  • Width: Length of a string.
  • Char: If you omit this argument, it considers white spaces as a default parameter. To change the default value, specify the Character you want to use in the remaining width.

Python rjust method Example

This string function accepts only one Character as a function second argument. The following set of examples helps you understand the Python rjust Function.

The following Str2 statement Justify the String variable Str1 to the Right-hand side, fill the remaining width with default white spaces, and print the output.

You may be confused with empty spaces, so we used ‘=’ as the second parameter for this Str3 variable. This Python statement fills the remaining width with the ‘=’ symbol.

The Python rjust function returns the output in a new string instead of altering the original string. To change the original String, write the following Method statement.

Str1 = Str1.rjust()

The Python rjust function only allows a single character as the second argument. Let us see what happens when we use two characters (+ and *) in Str4 and Str5.

The screenshot below shows that it is throwing an error saying: ‘TypeError: The fill character must be exactly one character long’.

Str1 = 'Tutorial Gateway';

Str2 = Str1.rjust(30)
print('Justifying Right with White sapces is =', Str2)

Str3 = Str1.rjust(30, '=')
print("Justifying Right with '=' using RJust() is =", Str3)

# Observe the Original
print('Converted String is =', Str1.rjust(30, '='))
print('Original String is =', Str1)

# Performing directly
Str4 = 'Tutorial Gateway'.rjust(30, '*')
print("Justifying Right with '*' using RJust() is =", Str4)

# Performing with two characters
Str5 = 'Tutorial Gateway'.rjust(30, '+*')
print('Justifying Right with + and * using RJust() is =', Str5)
Python RJust Function Example