Python String ljust()

The syntax of ljust() method is:

string.ljust(width[, fillchar])

Here, fillchar is an optional parameter.


String ljust() Parameters

ljust() method takes two parameters:

  • width - width of the given string. If width is less than or equal to the length of the string, the original string is returned.
  • fillchar (Optional) - character to fill the remaining space of the width

Return value from String ljust()

The ljust() method returns the left-justified string within the given minimum width.

If fillchar is defined, it also fills the remaining space with the defined character.


Example 1: Left justify string of minimum width

# example string
string = 'cat'
width = 5

# print left justified string
print(string.ljust(width))

Output

cat  

Here, the minimum width defined is 5. So, the resultant string is of minimum length 5.

And, the string cat is aligned to the left which makes leaves two spaces on the right of the word.


Example 2: Left justify string and fill the remaining spaces

# example string
string = 'cat'
width = 5
fillchar = '*'

# print left justified string
print(string.ljust(width, fillchar))

Output

cat**

Here, the string cat is aligned to the left, and the remaining two spaces on the right is filled with the character *.

Note: If you want to right justify the string, use rjust(). You can also use format() method for the formatting of strings.

Did you find this article helpful?