str.center()
Returns a copy of a string centred in a field of the width you choose, padded with spaces or another single character.
str.center(width, fillchar=' ', /)center() adds padding on both sides so the text sits in the middle of width characters. By default the padding is spaces; give a second argument to use another character, such as "*" or "=".
It is useful for headings in text reports, receipts and simple menus printed in the terminal.
If the padding cannot be split evenly, one side gets one more character. If the text is already as long as width or longer, it comes back unchanged. The fill character must be exactly one character.
Parameters
| Parameter | What it is |
|---|---|
widthrequired | The total length of the result. |
fillcharoptional, default ' ' | The single character used for padding. Pass it by position, as in center(20, "*"): writing fillchar= raises TypeError. |
Return value
A new string of length width (or the original, if it is longer).
Examples
1Centre with stars
print("Menu".center(20, "*"))
print("Menu".center(4, "*"))********Menu******** Menu
2Centre with spaces
print("|" + "Menu".center(12) + "|")| Menu |
The bars show the spaces on both sides.
3A receipt heading
width = 24
print("=" * width)
print(" RECEIPT ".center(width, "="))
print("Coffee".ljust(18) + "3.50".rjust(6))
print("=" * width)======================== ======= RECEIPT ======== Coffee 3.50 ========================
RECEIPT has 9 characters, so 15 are left: 7 go on one side and 8 on the other.
4A simple menu
options = ["Start", "Settings", "Quit"]
for o in options:
print("[" + o.center(10) + "]")[ Start ] [ Settings ] [ Quit ]
Common mistakes
Using more than one fill character
fillchar must be a single character, otherwise Python raises TypeError.
try:
print("Hi".center(10, "-="))
except TypeError:
print("TypeError: fillchar must be one character")
print("Hi".center(10, "-"))TypeError: fillchar must be one character ----Hi----
Questions people ask
How do I centre text with format() or an f-string?
Use ^: f"{text:^20}" or f"{text:*^20}" with a fill character.
How do I align left or right instead?
Use str.ljust() and str.rjust().
Can center() cut text that is too long?
No. Cut it yourself first: text[:width].center(width).