Python Principles

Explaining ljust

In Python, strings have a built-in method named ljust. The method lets you pad a string with characters up to a certain length.

The ljust method means "left-justify"; this makes sense because your string will be to the left after adjustment up to the specified length.

Examples

Here are some examples of using ljust:

>>> string = "hello"
>>> string.ljust(10, ".")
'hello.....'
>>> string.ljust(10, "X")
'helloXXXXX'
>>> string.ljust(20, "X")
'helloXXXXXXXXXXXXXXX'
>>> string.ljust(2, "X")
'hello'

Using ljust

As you can see in the examples above, the first argument to ljust is the length. After ljust has run, the output will be at least this long. However, if the string was already long enough, nothing will happen.

The second argument is the character to use for padding. The ljust method will continue appending this character to the string until it is long enough.

ljust without a second argument

If you leave out the second argument, ljust will use spaces for padding:

>>> "hello".ljust(8)
'hello   '

The opposite of ljust

The opposite of ljust is rstrip:

>>> "hello".ljust(8, "X")
'helloXXX'
>>> "hello".ljust(8, "X").rstrip("X")
'hello'

Note, however, that this may strip too many letters off your original string.

Right justification

If you want to right-justify your string, so that it ends up on the right-hand-side after padding, you should use rjust instead:

>>> "hello".rjust(8, "X")
'XXXhello'

Want to get better at Python?

Try our practical beginner lessons, or test your skills with our challenges.

View Lessons Try Challenges