In Python, strings have a built-in method named
ljust. The method lets you
pad a string with characters up to a certain length.
ljust method means "left-justify"; this makes sense because your string
will be to the left after adjustment up to the specified length.
Here are some examples of using
>>> string = "hello" >>> string.ljust(10, ".") 'hello.....' >>> string.ljust(10, "X") 'helloXXXXX' >>> string.ljust(20, "X") 'helloXXXXXXXXXXXXXXX' >>> string.ljust(2, "X") 'hello'
As you can see in the examples above, the first argument to
ljust is the
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
will continue appending this character to the string until it is long enough.
If you leave out the second argument,
ljust will use spaces for padding:
>>> "hello".ljust(8) 'hello '
The opposite of
>>> "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.
If you want to right-justify your string, so that it ends up on the
right-hand-side after padding, you should use
>>> "hello".rjust(8, "X") 'XXXhello'
Try our practical beginner lessons, or test your skills with our challenges.