Python String ljust() method left aligns the string according to the width specified and fills the remaining space of the line with blank space if ‘fillchr‘ argument is not passed.
Python String ljust() Method Syntax:
Syntax: ljust(len, fillchr)
Parameters:
- len: The width of string to expand it.
- fillchr (optional): The character to fill in the remaining space.
Return: Returns a new string of given length after substituting a given character in right side of original string.
Python String ljust() Method Example:
Python3
string = "Lazyroar" print (string.ljust( 10 , '-' )) |
Output:
Lazyroar-----
Example 1: Basic Example of Using Python String ljust() Method
Python3
# example string string = 'gfg' width = 5 # print left justified string print (string.ljust(width)) |
Output:
gfg
Explanation:
Here, the minimum width defined is 5. So, the resultant string is of minimum length 5. And, the string ‘gfg’ is aligned to the left, which makes leaves two spaces on the right of the word.
Example 2: Printing Formatted table using Python String ljust() Method
Here, we use Python String ljust() method to make each item of equal width of max 10 characters. We have used 10 here because all items are less than 10 characters, for evenly formatting.
Python3
# our list of data l = [ [ 'Name' , 'Age' , 'Code' ], [ 'Tuhin' , 21 , '+855-081' ], [ 'Kamal' , 22 , '+976-254' ], [ 'Arjun' , 22 , '+759-255' ] ] # iterate on each row of the list for row in l: for item in row: # print each item after space adjustment using ljust print ( str (item).ljust( 10 , ' ' ), end = "") # add new line after each row printing print () |
Output:
Name Age Code Tuhin 21 +855-081 Kamal 22 +976-254 Arjun 22 +759-255