bytes.zfill(width) returns a copy of the data padded on the left with ASCII zero bytes (b"0", value 48) until it is width bytes long.
If the data starts with a sign byte, b"+" or b"-", the zeros are inserted after the sign, so b"-42" becomes b"-0042". If the data is already at least width long, it is returned unchanged.
bytes.zfill() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.zfill(...). No import is needed, and bytearray objects have the same method.
Syntax
Pass the total width you want.
python
result = data.zfill(width)
Call
What it does
b"7".zfill(3)
Returns b'007'.
b"-42".zfill(5)
Returns b'-0042'.
b"12345".zfill(3)
Returns b'12345': never truncates.
zfill() does not check that the data is numeric; it pads any bytes.
Method signatures
python
bytes.zfill(width)
# returns a new bytes object (bytearray.zfill() returns a bytearray)
Parameters
Parameter
Description
width
The minimum length of the result in bytes.
Return Value
Return Value
Description
bytes
A copy padded with ASCII zeros on the left (after any sign) to width bytes.
Python Examples
Example 1 — Pad Counters and Signed Values
Pad a small counter, a negative and a positive signed value, and a value that is already long enough.