Skip to main content

Python String ljust() Function

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

note

The original string is returned as it is, if width parameter is less than or equal to string length.

Syntax

my_string.ljust(width, fillchar)

ljust() Parameters

Python String ljust() function parameters:

ParameterConditionDescription
widthRequiredThe length of the string
fillcharOptionalA character you want to use as a fill character. Default value is an ASCII space.
note

If fillchar is not provided, a whitespace is taken as the default argument.

ljust() Return Value

Python String ljust() function 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******