Python Reference ยท String Methods
Python str.ljust() method
Reference for Python str.ljust(): pad a string on the right to a minimum width with spaces or a fill character, for aligned text columns and simple reports.
The ljust() method returns a string of at least a given width, with the original text on the left and padding added on the right. It is a quick way to line up columns of plain text.
If the string is already as long as the width or longer, nothing is added and the original string is returned unchanged. It never truncates.
print("cat".ljust(6) + "|") # cat |
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.ljust(width, fillchar=" ")
| Name | Description |
|---|---|
width |
The minimum length of the result. If it is less than or equal to len(str), the string is returned as is. |
fillchar |
Optional. A string of exactly one character used for padding. The default is a space. |
Return value: a string of length max(width, len(str)). Strings are immutable, so the original is not changed.
Raises: TypeError if fillchar is not exactly one character long or width is not an integer.
Usage notes
- Pads, never cuts. Use slicing, such as
text[:width].ljust(width), to enforce a fixed width. - Counts code points. Width is measured in characters, not in display columns. Emoji and East Asian wide characters can look misaligned in monospaced output.
- One fill character only. Passing
"ab"raisesTypeError. Build longer patterns with multiplication, like"-" * n. - Mirror methods.
rjust()pads on the left,center()on both sides, andzfill()pads numbers with zeros after the sign. - f-strings are often neater.
f"{name:<12}"does the same thing and combines with other format options.ljust()is better when the width is computed or you want a plain method call, for example insidemap(). - Dynamic widths. Find the longest label first,
width = max(map(len, labels)), then use it for everyljust(width).