Python ljust function is used to Justify the string to the left-hand side. And fill the remaining width with specified character (by default, white spaces) and returns the new string. In this section, we discuss how to write ljust with an example.
The syntax of the ljust function is
- Width: Please specify the Justifying 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 ljust method Example
The ljust Function accepts only one Character as a function second argument. The following set of examples helps you understand the Function.
The following Str2 statement Justifies the String variable Str1 to the left-hand side. And fill the remaining width with default white spaces and print the output.
You may be confused with empty spaces, that’s why we used ‘=’ as the second parameter. This Python Str3 statement fills the remaining width with the ‘=’ symbol.
The Python ljust function returns the output in a new string instead of altering the original string.
To change the original String, write the following String Method statement.
Str1 = Str1.ljust()
The ljust 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.
It is throwing an error saying: ‘TypeError: The fill character must be exactly one character long’.
Str1 = 'Tutorial Gateway' Str2 = Str1.ljust(30) print('Justifying Left with White sapces is =', Str2) # Let us place second parameter as well Str3 = Str1.ljust(30, '=') print("Justifying Left with '=' using is =", Str3) # Observe the Original String print('Converted String is =', Str1.ljust(30, '=')) print('Original String is =', Str1) # Performing directly Str4 = 'Tutorial Gateway'.ljust(30, '*') print("Justifying Left with '*' using is =", Str4) # Performing with two characters Str5 = 'Tutorial Gateway'.ljust(30, '+*') print('Justifying Left with + and * using is =', Str5)