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 example and the syntax is
- Width: Length of a string.
- Char: If you omit this argument, it 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.
Python rjust method Example
It accepts only one Character as a function second argument. The following set of examples help you understand the Python rjust Function.
The following Str2 statement Justify the String variable Str1 to the Right-hand side and fill the remaining width with default white spaces and prints the output.
You may be confused with empty spaces, that’s why we used ‘=’ as the second parameter for this Str3 variable. This Python statement fills the remaining width with the ‘=’ symbol.
The rjust function returns the output in a new string, instead of altering the original string. 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 *) in Str4 and Str5.
From the below screenshot, you can observe 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 String 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)