Python String ljust
Now, we are going to learn about the ljust method. With this method, we get our string as left justified, in a string of length width, which is provided as an argument to the ljust method. Padding is done using the specified padding character (if not specified, it defaults to whitespace). Let’s have a look at a simple example, which demonstrates the same thing.
Python String ljust() Method
As you can see in the above program, we have a string, and then we are trying to call the ljust method on the string. The width is given as an argument to the method, which is 20 in our case, and we also have specified a padding character, which is ‘@’ in our case. So, the string that we get as a return value from the ljust method is a left justified string with length 20 in our case, which is the width, and the padding is done by the specified padding character.
Let’s have a look at the output now –
GyaniPandit@@@@@@@@@
As you can see in the output, we have a left-justified string, with a length of 20, and the padding is done with the padding character.
If the width that we provide as an argument to the ljust method is less than or equal to the length of the string, then the original string is returned. Let’s have a look at the example, which demonstrates the same thing.
As you can see in the above program, we again have the string, and then we are again calling the ljust method. This time, the width which is passed is less than the length of the string. In such a situation, the return value from the method is the same string.
So, as and when required, we can make use of the ljust method, which returns the left justified string of the length, which is given as an argument to the method.