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 ljust Function in Python Programming with example.

Python ljust Syntax

The syntax of the Python ljust function is

String_Value.ljust(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, ljust 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.

Python ljust method Example

The following set of examples help you understand the ljust Function in Python.

NOTE: The ljust Function accepts only one Character as a function second argument

# Python LJust Method Example

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 LJust() is =", Str3)

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

# Performing LJust() function directly
Str4 = 'Tutorial Gateway'.ljust(30, '*')
print("Justifying Left with '*' using LJust() is =", Str4)

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

The following statement Justifies the String variable Str1 to the Left-hand side. And fill the remaining width with default white spaces using the ljust function and prints the output.

Str2 = Str1.ljust(30)
print('Justifying Left 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.ljust(30, '=')
print("Justifying Left with '=' using LJust() is =", Str3)

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

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

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

Str1 = Str1.ljust()

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

Str5 = 'Tutorial Gateway'.ljust(30, '+*')
print('Justifying Left with + and * using LJust() is =', Str5)

It is throwing an error saying: ‘TypeError: The fill character must be exactly one character long’