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'

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!

Learn more about the course

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!