Python Glossary Русский

all Python 3Byte sequencesfunction

bytes.center

bytes — padding

Center the bytes in a field of the given width using a fill byte.

Syntax

b.center(...)

The fill has to be exactly one byte: b'ab' or an empty value raise TypeError, and a plain str like '*' is rejected outright — it must be bytes. The method never truncates; if width is smaller than the data, the original object comes back unchanged. When the padding does not split evenly the extra byte lands asymmetrically and which side gets it depends on the parity of width, so reach for ljust() or rjust() when the exact layout matters.

Examples

print(b'hi'.center(6, b'*'))   # → b'**hi**'
print(b'hi'.center(6))   # → b'  hi  '
print(b'ab'.center(5, b'-'))   # → b'--ab-'
print(b'hello'.center(3, b'*'))   # → b'hello'
print(b'hi'.rjust(6, b'.'))   # → b'....hi'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy