What is ljust() in Python?
The ljust() method in Python is a string function that returns a left-justified string with a length equal to the specified width.
Syntax
The syntax of this function is as follows:
string.ljust(width, char)
Parameters and Return value
The ljust() method takes two parameters, which are described below:
- width (required): This argument defines the total length of the string that is required. If it is smaller or equal to the current length of the string, the function returns the same string.
- char (optional): It is the character that is added to the string to increase its length according to the specified width. If this is not specified, empty spaces are added to the string.
The return value is a copy of the string with extended length.
Code
In the code below, when no fill character is specified, ljust() is adding empty spaces to string ‘hello’ and extends its length to 7. Consequently, if the character ‘/’ is defined in the function, it adds ‘/’ to extend the length of the string to the specified value ljust().
# example stringstring = 'hello'# without any fill character, adding empty spacesx = string.ljust(7)print(x , 'with length', len(x))# with fill character, adding '/'y = string.ljust(7, '/')print(y , 'with length', len(y))