my_string.ljust(width, filler)
width
: left justified string of width filler
: optional, string can be used to fill the width
my_str='Welcome to'
output=my_str.ljust(15,'*')
print(output) # Welcome to*****
my_str='Welcome to'
output=my_str.ljust(5,'*')
print(output) # Welcome to
If the string is longer than the specified width, ljust() leaves it unchanged:
my_str = 'Python'
print(my_str.ljust(4, '*')) # Output: 'Python'
You can use ljust() to format columns in a table:
header = "Name".ljust(10) + "Age".ljust(5)
row = "Alice".ljust(10) + "25".ljust(5)
print(header)
print(row)
Name Age
Alice 25
ljust() can fill extra space with any character:
text = 'Data'
print(text.ljust(10, '-')) # Output: 'Data------'
Aligning text output for a CLI application:
item = "Product".ljust(15, '.') + "Price"
print(item) # Output: 'Product.......Price'
Aligning log entries for readability:
log_entry = "INFO".ljust(8) + "Operation completed."
print(log_entry)# Output: 'INFO Operation completed.'