bytes.rjust(width, fillbyte) returns a copy of the data with fill bytes added on the left until it is width bytes long. The default fill is an ASCII space.
Right alignment suits numbers: amounts, sizes, and offsets line up on their last digit. With b"0" as the fill it zero-pads, but unlike zfill() it does not treat a sign specially.
bytes.rjust() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.rjust(...). 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.rjust(width)
result = data.rjust(width, fillbyte)
Call
What it does
b"42".rjust(5)
Returns b' 42'.
b"ff".rjust(4, b"0")
Returns b'00ff'.
b"12345".rjust(3)
Returns b'12345'.
Data already at least width bytes long is returned unchanged.
Method signatures
python
bytes.rjust(width, fillbyte=b' ', /)
# returns a new bytes object (bytearray.rjust() 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 left. Default b" ".
Return Value
Return Value
Description
bytes
The data padded on the left to width bytes.
Python Examples
Example 1 — Right-Align Amounts in a Receipt
Convert each amount to ASCII bytes and right-align it in six bytes so the digits line up.
python
for amount in [5, 120, 98765]:
print(str(amount).encode("ascii").rjust(6) + b" EUR")
Output
b' 5 EUR'
b' 120 EUR'
b' 98765 EUR'
How It Works
Number to bytes.str(amount).encode("ascii") produces the digits as bytes.
Last digits aligned. Each value is padded on the left to six bytes, so units line up.
Add a suffix. Concatenating b" EUR" keeps the result as bytes.
Example 2 — Zero Padding with rjust() and zfill()
Both can add leading zeros, but they treat a minus sign differently.