String ljust() Method in Python

Python String ljust() Method

The ljust() method in Python is used to left-justify a string within a specified width by padding it with a specific character on the right side. It returns a new string that is the original string aligned to the left and padded with the specified character to meet the given width.Here's the syntax of the ljust() method:

string.ljust(width, fillchar)

Parameters:

  • width: The width of the resulting string, including the length of the original string and any additional padding characters.
  • fillchar (optional): The character used for padding. If not specified, it defaults to a space character (' ').

Example:

# Example using ljust() method
text = "Python"
width = 10

result = text.ljust(width)

print("Original text:", text)
print("Left-justified text:", result)

Output:

Original text: Python
Left-justified text: Python    

In this example, the original text is "Python", and we want to left-justify it within a width of 10 characters. Since the original text is only 6 characters long, the ljust() method pads the text with spaces on the right side until it reaches the width of 10 characters. The resulting string is "Python ".

The ljust() method is useful when you want to align strings to the left and add padding characters to ensure consistent formatting, especially when displaying text in a tabular format or when creating fixed-width output.