bytes.center()
Centring with an odd byte to spare is where the surprise lives: sometimes the extra goes left, sometimes right, and the rule is not "always left".
Demo
When the padding splits evenly the result is symmetric. Compare the two odd cases carefully: ab centred to 7 gets the extra star on the LEFT, but abc centred to 6 gets it on the RIGHT. CPython puts the extra byte on the left only when the data length and the width have different parity — it is not a fixed side. Data already at or beyond the width comes back unchanged, and a fill that is not exactly one byte raises TypeError.
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. Longer or shorter raises TypeError. |
Return value
bytes — A new bytes object padded on both sides to at least width. Never truncates. When the padding cannot be split evenly, which side gets the extra byte depends on a parity rule.
Common patterns
line = title.center(80, b'=')
banner = b' ' + label + b' ' banner = banner.center(40, b'-')
text.decode('utf-8').center(20).encode('utf-8')
Examples
Pitfalls
b'ab'.center(7, b'*'), b'abc'.center(6, b'*')
pad = width - len(d) b'*' * (pad // 2) + d + b'*' * (pad - pad // 2)
b'ab'.center(6, '·'.encode())
b'ab'.center(6, b'.')
'é'.encode().center(5, b'*')
'é'.center(5, '*').encode()
When to use
- Fixed-width ASCII report and banner output
- Aligning a label inside a byte-based line
- Text with non-ASCII characters → decode, centre, encode
- You need a predictable odd-padding side → pad manually
- A non-ASCII fill character — it must be one byte
Notes
FAQ
CPython computes the left padding as half the total plus an adjustment based on the parity of both the width and the data length. When the two parities differ, the extra byte goes left; when they match, it goes right. It is deliberate but not obvious, and str.center follows the same rule.
b'ab'.center(7, b'*') # b'***ab**' b'abc'.center(6, b'*') # b'*abc**'