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 = "geeks"
print (string.ljust( 10 , '-' ))
|
Output:
geeks-----
Example 1: Basic Example of Using Python String ljust() Method
Python3
string = 'gfg'
width = 5
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
l = [
[ 'Name' , 'Age' , 'Code' ],
[ 'Tuhin' , 21 , '+855-081' ],
[ 'Kamal' , 22 , '+976-254' ],
[ 'Arjun' , 22 , '+759-255' ]
]
for row in l:
for item in row:
print ( str (item).ljust( 10 , ' ' ), end = "")
print ()
|
Output:
Name Age Code
Tuhin 21 +855-081
Kamal 22 +976-254
Arjun 22 +759-255
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!