Python String ljust() Method

The ljust() method returns the left justified string with the specified width. If the specified width is more than the string length, then the string's remaining part is filled with the specified fill char. The default fill char is a space. The original string is returned if the width is less than the length of the given string.

Syntax:

str.ljust(width, fillchar)

Parameters:

  1. width : (Required) The length of the left justified string.
  2. fillchar : (Optional) character to fill the remaining space of the left justified string if the width is more than its length.

Return Value:

Returns a left justified string.

The following example demonstrates the ljust() method.

Example: ljust()
>>> mystr = 'Hi'
>>> mystr.ljust(4)
'Hi  '
>>> mystr.ljust(4, '-')
'Hi--'
>>> mystr.ljust(2, '-')
'Hi'

In the above example, mystr.ljust(4) creates a new string of length 4 and make 'Hi' left justified. A fillchar is not mentioned; therefore, the default value space is used. So, the result is 'Hi ' with 2 spaces on the right side. In the same way, mystr.ljust(4, '-') results in 'Hi--'. The total length of a new string is 4 and appends two '-' chars as a fillchar.

If the given width is the same or less than the original string, then the ljust() method does nothing and returns the original string, as shown below.

Example: ljust()
>>> mystr = 'Hello'
>>> mystr.ljust(2)
'Hello'
>>> mystr.ljust(2,'*')
'Hello'
>>> mystr.ljust(5,'*')
'Hello'

The fillchar parameter must be a single character. If given more than one chars as fillchar then it will throw a TypeError, as shown below.

Example: ljust()
>>> mystr = 'Hello World'
>>> mystr.ljust(20,'->')
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    'Hello World'.ljust(20,'->')
TypeError: The fill character must be exactly one character long