Python String ljust() Method – Tutorial with Examples

Python String ljust() Method

Python provides various string methods to perform operations on strings. One of them is the ljust() method. The ljust() method is used to left-justify a string to a specified width by padding it with a specified character on the right side.

Syntax

The syntax for using the ljust() method is as follows:

str.ljust(width[, fillchar])

Here’s what the parameters do:

  • width – Required. An integer that specifies the width of the resulting string, including the original string and any padding characters.
  • fillchar – Optional. A character that will be used to pad the original string. The default value is a space character (' ').

The ljust() method returns a new string that is left-justified to the specified width by padding it with the specified character on the right side.

Examples

Here are some examples to illustrate the usage of the ljust() method:

Example 1: Left-justifying a string with default padding

# Left-justify a string to a width of 20 with default padding
string = "hello"
justified = string.ljust(20)
print(justified)

Output:

hello               

The ljust() method is used to left-justify the string “hello” to a width of 20. Since no padding character is specified, the default padding character (a space) is used to pad the original string on the right side.

Example 2: Left-justifying a string with a specified padding character

# Left-justify a string to a width of 10 with padding character '-'
string = "hello"
justified = string.ljust(10, '-')
print(justified)

Output:

hello-----

The ljust() method is used to left-justify the string “hello” to a width of 10. The padding character ‘-‘ is specified, so the original string is padded with ‘-‘ characters on the right side to reach the specified width.

Example 3: Left-justifying a string that is already wider than the specified width

# Left-justify a string to a width of 3 with default padding
string = "hi how are you?"
justified = string.ljust(3)
print(justified)

Output:

hi how are you?

The ljust() method is used to left-justify the string “hi” to a width of 3. However, since the original string is already wider than the specified width, no padding is added on the right side.

Use Cases

The ljust() method can be useful in situations where you need to format strings to a specific width, such as when printing tables or aligning text in a user interface. It can also be used to add padding to the right side of strings so that they all have the same width, making them easier to compare and read.

Leave a Reply

Your email address will not be published. Required fields are marked *