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.
The syntax of ljust() is as below :
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.
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.
Let’s try to understand ljust with an example :
str_1 = "Hello" print(str_1.ljust(10,'$')) print(str_1.ljust(10)) print(str_1.ljust(3,'$'))
It will print the below output :
Hello$$$$$ Hello Hello
- 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.
- The second print statement actually printed one string of 10 characters. The first five characters are ‘Hello’ and the last five characters are space.
- The last print statement printed the string ‘Hello’ as the value of width is 3 which is less than the string size.
- Python string center method explanation with example
- Python set isdisjoint() explanation with an example
- Python set discard method explanation with an example
- Python gamma() function explanation with example
- Python Set difference_update explanation with an example
- Python Set pop() method explanation with example