Python String ljust() Method
The ljust() method returns a left-justified original string, padded with Spaces to a new string of the specified length. Returns the string if the specified length is less than the length of the string.
Python String ljust() Syntax
Syntax for the ljust() method:
str.ljust(width[, fillchar])
Python String ljust() Parameters
- width – Specifies the length of a string.
- fillchar – Filling character, default space.
Python String ljust() Return Value
Returns a string left justified and padded with Spaces to a new string of specified length. Returns the string if the specified length is less than the length of the string.
Python String ljust() Example#1
The following example shows the use of ljust() :
#!/usr/bin/python3
str1 = "Apidemos example....wow!"
print (str1.ljust(50, '*'))
Output:
Python String ljust() Example#2
Print the formatted table using the Python string ljust() method.
Here, we use the Python String ljust() method to make each item equal in width, up to a maximum of 10 characters. We used 10 here because all the items are less than 10 characters long to format evenly.
#!/usr/bin/python3
l = [
['Name', 'Age', 'Code'],
['Api', 21, '+855-081'],
['Demos', 22, '+976-254'],
['Com', 22, '+759-255']
]
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: