What is a string.ljust in Python?

The ljust method returns a left-justified string of length as width by adding a specified fill character to the end of the string.

Syntax

string.ljust(width, fillchar)

Parameters

  • width: The resulting string length.

  • fillchar: Fill character to be added at the end of the string. It is an optional value. By default, the space will be added.

Return Value

  • If the width is greater than the length of the string then the specified fill character will be added at the end of the string to make the string length equal to the passed width value.

  • If the width is greater than the length of the string then the original string is returned.

Example

string = "123"
print(string.ljust(4, '$'))
print(string.ljust(5, '*'))
print(string.ljust(10, '#'))
print(string.ljust(1, '#'))

In the code above, we created a 123 string and then:

  • Called ljust method where the width is 4 and fillchar is . In this case, the string length is three, and the width is four. Four is greater than three and 4-3 = 1, so one is added to the end of the string and 123$ is returned.

  • Called ljust method where the width is 5 and fillchar is *. In this case, the string length is three, and the width is Five. Five is greater than three and 5-3 = 2, so two * are added to the end of the string and 123** is returned.

  • Called ljust method where the width is 10 and fillchar is #. In this case, the string length is three, and the width is ten. Ten is greater than three and 10-3 = 7, so seven # are added to the end of the string and 123####### is returned.

  • Called ljust method where the width is 1 and fillchar is #. In this case, the string length is three, and the width is one. One is smaller than three, so the string and 123 will be returned.

Free Resources