Python rjust

Python rjust method is used to Justify the string to the Right-hand side 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 rjust Function with example.

Python rjust Syntax

The syntax of the Python rjust function is

String_Value.rjust(Width, Char)
  • String_Value: Please select the valid String literal.
  • Width: Please specify the Justifying length of a string.
  • Char: This parameter is optional, and if you omit this, the rjust Function considers the white spaces as a default parameter. To change the default value, Please specify the Character you want to use in the remaining width.

NOTE: The rjust Function accepts sonly one Character as a function second argument.

Python rjust method Example

The following set of examples help you understand the rjust Function.

# Python RJust Method Example

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 String
print('Converted String is =', Str1.rjust(30, '='))
print('Original String is =', Str1)

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

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

The following statement Justify the String variable Str1 to the Right-hand side and fill the remaining width with default white spaces using rjust function and prints the output.

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

You may be confused with empty spaces, that’s why we used ‘=’ as the second parameter. This Python statement fills the remaining width with the ‘=’ symbol.

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

The Python rjust function returns the output in a new string, instead of altering the original string.

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

From the above screenshot, you can observe that the original string Str1 is unchanged. If you want to change the original String then, you can write the following String Method statement

Str1 = Str1.rjust()

The Python rjust function only allows a single character as the second argument. Let us see what happen when we used two characters (+ and *).

Str5 = 'Tutorial Gateway'.rjust(30, '+*')
print('Justifying Right with + and * using RJust() is =', Str5)

From the above rjust screenshot, you can observe that it is throwing an error saying: ‘TypeError: The fill character must be exactly one character long’