bytes.ljust()
The name describes where the DATA sits, not where the padding goes. Left-justified data means the padding is on the right — a lifelong source of confusion.
Demo
The data stays at the left edge and fill bytes are added on the right until the width is reached. Data that already meets or exceeds the width comes back unchanged — ljust never cuts anything off. Empty data becomes pure fill. The fill must be a single byte, exactly as with center and rjust.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| width | int | yes | Minimum total length. Shorter widths return the data unchanged. |
| fillbyte | bytes | no (b' ') | A bytes object of length exactly 1. Anything else raises TypeError. |
Return value
bytes — A new bytes object padded on the right with fillbyte to at least width. Data already that long is returned unchanged.
Common patterns
row = name.ljust(20) + amount.rjust(10)
field = value.ljust(FIELD_LEN, b'\x00')
line = title.ljust(60, b'.') + page
Examples
Pitfalls
b'42'.ljust(5, b'0')
b'42'.rjust(5, b'0')
b'toolong'.ljust(4)
b'toolong'[:4].ljust(4)
'é'.encode().ljust(3, b'-')
'é'.ljust(3, '-').encode()
When to use
- Left-aligned columns in fixed-width byte output
- Padding a field to a required length
- Dot leaders and similar alignment
- Padding on the LEFT → rjust
- Text with non-ASCII characters → decode, pad, encode
- A hard width limit → slice first, since ljust never truncates
Notes
FAQ
Because it LEFT-justifies the data — pushes it to the left edge — and whatever space remains is on the right. Think of it as text alignment in a word processor: left-aligned text has ragged space on the right.
b'ab'.ljust(5, b'-') # b'ab---'