Python string ljust() method explanation with example

Python string ljust() :

The ljust() word stands for left-justified. It returns a left-justified string of a given width. It uses one specific character called fill character to fill the additional position of the string. The default value of fill character is space.

In this tutorial, we will learn how ljust() works in python with example.

Syntax of ljust() :

The syntax of ljust() is as below :

str.ljust(width[, fillchar])

As you can see, ljust takes a maximum of two parameters : width: This is the final string length after padding. fillchar: This is an optional parameter. It is the character used to fill the string. The default value of this value is space.

Return value of ljust :

ljust will return the left-justified string of size width filled the extra positions with fillchar. If fillchar is not provided, it will fill the position with space.

One thing to note here is that if the value of width is less than the size of the string, i.e. if we want the final string size less than the original string, it will return the string without doing any padding to it.

Examples :

Let’s try to understand ljust with an example :

str_1 = "Hello"


It will print the below output :


python ljust

Explanation :

  1. For the first print statement of the above example, the value of width is 10 and the fillchar is ’$’. The given string is ‘Hello’. This string has only 5 characters. So, 5 more ’$’ characters are added to the right to make the final string length 10.
  2. The second print statement actually printed one string of 10 characters. The first five characters are ‘Hello’ and the last five characters are space.
  3. The last print statement printed the string ‘Hello’ as the value of width is 3 which is less than the string size.

Similar tutorials :