how to use python string ljust() with example

The ljust() method in Python is a string method that aligns the string to the left by padding it with a specified character or whitespace to reach a specified width. The method returns a new string that contains the original string aligned to the left with the added padding.

Syntax:

string.ljust(width, fillchar)

string: This is the original string that you want to align to the left.

width: It specifies the width of the resulting aligned string. If the original string is shorter than the specified width, it will be left-aligned and padded to the specified width.

fillchar (optional): This parameter defines the padding character or string to use for the alignment. It is an optional parameter, and if not provided, it defaults to a space character.

How to use the ljust() method:

text = "Hello"
padded_text = text.ljust(10, "-")
print(padded_text)

Output:

Hello-----

Example 1

Generating text-based progress bars.

progress = 75
total = 100

progress_bar = "[" + "#" * (progress // 5) + "]"
progress_bar = progress_bar.ljust(20, "-")
print(progress_bar)

Output:

[####################]----

Example 2

Formatting text output.

items = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]

print("Items:")
for item in items:
  print("- " + item.ljust(12) + " -")

Output:

Items:
- Apple    -
- Banana   -
- Cherry   -
- Date    -
- Elderberry -