Python ljust

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 Python ljust with an example.

The syntax of the Python ljust function is

  • Width: Please specify the Justifying 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.
String_Value.ljust(Width, Char)

Python ljust method Example

The Python 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, so 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 throws 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)
Python LJust string function