Skip to content

Python String ljust() Method

How to use Python's ljust() method to left-justify strings with custom padding and default whitespace, including handling edge cases like width constraints.

The String ljust() method returns left-justified string of length width. Padding is done using the specified fillchar (default value is an ASCII space).

Syntax

my_string.ljust(width, fillchar)

ljust() Parameters

Python String ljust() method parameters:

Parameter Condition Description
width Required The length of the string
fillchar Optional A character you want to use as a fill character. Default value is an ASCII space.

ljust() Return Value

Python String ljust() method returns a new string that is left-justified within a string of the specified length, using the specified fill character.

Examples

Example 1: Left-Justify a String using ljust() method

By default, the string is padded with whitespace (ASCII space, ).

my_str = 'Left'
result = my_str.ljust(10)
print(f"'{result}'") # Output: 'Left      '

output

'Left      '

Example 2: Left-Justify a String with Custom Padding

You can modify the padding character by specifying a fill character.

For example, left-justify a string with * as a fill character

my_str = 'Left'
result = my_str.ljust(10, '*')
print(f"'{result}'") # Output: 'Left******'

outputs

'Left******'

Example 3: Left-Justify a String with too small width

If the width is less than or equal to string length, then the original string is returned.

my_str = 'Left'
result = my_str.ljust(2, '*')
print(f"'{result}'") # Output: 'Left'

output

'Left'

Equivalent Method to Left-Justify a String

You can left-justify a string as you would do with ljust() method by using format() method.

For example, using the ljust() method:

my_str = 'Left'
result = my_str.ljust(10, '*')
print(result) # Output: Left******

output

Left******

This is equivalent to the use of format() method:

my_str = 'Left'
result = '{:*<10}'.format(my_str)
print(result) # Output: Left******

output

Left******
Navigation