String method

str.ljust()

Returns a copy of a string padded on the right to the width you choose, so the text lines up on the left side.

BeginnerEvery example below runs in your browser. Change the code and press Run.

str.ljust(width, fillchar=' ', /)

ljust() ("left-justify") adds padding after the text until it is width characters long. The text stays at the left, which is how you line up columns of names or labels.

Give a second argument to pad with another character, such as dots in a table of contents: "Chapter 1".ljust(20, ".").

It never cuts: if the text is already longer than width, you get it back unchanged, and your columns will no longer line up. The fill character must be exactly one character.

Parameters

ParameterWhat it is
width
required
The total length of the result.
fillchar
optional, default ' '
The single character used for padding. Pass it by position, as in ljust(20, "."): writing fillchar= raises TypeError.

Return value

A new string of length width (or the original, if it is longer).

Examples

1Pad with spaces

Pythoneditable
print("[" + "cat".ljust(8) + "]")
print("[" + "elephant".ljust(4) + "]")
Output
[cat     ]
[elephant]

2Line up a price list

Pythoneditable
items = [("Coffee", "3.50"), ("Sandwich", "6.25"), ("Water", "1.00")]
for name, price in items:
    print(name.ljust(10) + price)
Output
Coffee    3.50
Sandwich  6.25
Water     1.00

3Dot leaders, like a table of contents

Pythoneditable
chapters = [("Introduction", 1), ("Variables", 7), ("Loops", 15)]
for title, page in chapters:
    print(title.ljust(16, ".") + str(page).rjust(3, "."))
Output
Introduction......1
Variables.........7
Loops............15

4Width from the longest item

Pythoneditable
names = ["Ana", "Bartholomew", "Li"]
w = max(len(n) for n in names)
for n in names:
    print(n.ljust(w), "|")
Output
Ana         |
Bartholomew |
Li          |

Common mistakes

Text longer than the width breaks the columns

ljust() does not cut. Compute the width from the data, or cut the text first.

Pythoneditable
for name in ["Ana", "Maximilian"]:
    print(name.ljust(6) + "|")
    print(name[:6].ljust(6) + "|")
Output
Ana   |
Ana   |
Maximilian|
Maximi|

Questions people ask

How do I pad on the left instead?

Use str.rjust(): the text then lines up on the right.

Is there an f-string version?

Yes: f"{name:<10}" pads to 10 characters on the right, f"{name:.<10}" with dots.

Why do my columns still not line up?

Some characters, like emoji or Chinese characters, are shown wider than one column in many terminals, while ljust() counts characters.

Spotted a mistake on this page? Tell us