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
widthis greater than thelengthof the string then the specified fill character will be added at the end of the string to make the string length equal to the passedwidthvalue. -
If the
widthis greater than thelengthof 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
ljustmethod where thewidthis4andfillcharis$. 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 and123$is returned. -
Called
ljustmethod where thewidthis5andfillcharis*. 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 and123**is returned. -
Called
ljustmethod where thewidthis10andfillcharis#. 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 and123#######is returned. -
Called
ljustmethod where thewidthis1andfillcharis#. In this case, the string length is three, and the width is one. One is smaller than three, so the string and123will be returned.