bytes.ljust(width, fillbyte) returns a copy of the data followed by enough fill bytes to make it width bytes long. The default fill is an ASCII space.
It is ideal for fixed-width records: binary formats often store names in a fixed-size field padded with zero bytes, and text reports use it to line up columns. Data that is already long enough is returned unchanged.
bytes.ljust() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.ljust(...). No import is needed, and bytearray objects have the same method.
Syntax
Give the field width and, optionally, a one-byte fill.
python
result = data.ljust(width)
result = data.ljust(width, fillbyte)
Call
What it does
b"id".ljust(5)
Returns b'id '.
b"ada".ljust(6, b"\x00")
Returns b'ada\x00\x00\x00'.
b"toolong".ljust(3)
Returns b'toolong'.
To make a field exactly n bytes even when the data is longer, slice first: data[:n].ljust(n, b"\x00").
Method signatures
python
bytes.ljust(width, fillbyte=b' ', /)
# returns a new bytes object (bytearray.ljust() returns a bytearray)
Parameters
Parameter
Description
width
The minimum length of the result in bytes.
fillbyte
Optional. A single byte used for padding on the right. Default b" ".
Return Value
Return Value
Description
bytes
The data padded on the right to width bytes.
Python Examples
Example 1 — Pack Names into Fixed 8-Byte Records
Each name gets an 8-byte slot padded with zero bytes, so any record can be found by its offset.
python
names = [b"ada", b"grace", b"linus"]
record = b"".join(n.ljust(8, b"\x00") for n in names)
print(len(record))
print(record[:8])
print(record[8:16].rstrip(b"\x00"))
Output
24
b'ada\x00\x00\x00\x00\x00'
b'grace'
How It Works
Equal slots. Three names times 8 bytes gives a 24-byte record.
Visible padding. The first slot shows ada followed by five zero bytes.
Read back. Slicing the second slot and calling rstrip() recovers the name.
Example 2 — Print a Dotted Status Table
Pad interface names with dots so the states line up, then decode each line for display.
python
items = [(b"eth0", b"up"), (b"wlan0", b"down"), (b"lo", b"up")]
for name, state in items:
print((name.ljust(8, b".") + state).decode("ascii"))
Output
eth0....up
wlan0...down
lo......up
How It Works
Same start column. Every state begins at column 8 because each name is padded to 8 bytes.
Concatenate bytes.+ joins the padded name and the state into one bytes object.
Print text.decode() removes the b'...' wrapper from the output.
Example 3 — Long Data and bytearray Results
See that ljust() leaves long data alone, mark the padding with a bar, and call it on a bytearray.