String method

str.center()

Returns a copy of a string centred in a field of the width you choose, padded with spaces or another single character.

BeginnerEvery example below runs in your browser. Change the code and press Run.

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

ParameterWhat it is
width
required
The total length of the result.
fillchar
optional, 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

Pythoneditable
print("Menu".center(20, "*"))
print("Menu".center(4, "*"))
Output
********Menu********
Menu

2Centre with spaces

Pythoneditable
print("|" + "Menu".center(12) + "|")
Output
|    Menu    |

The bars show the spaces on both sides.

3A receipt heading

Pythoneditable
width = 24
print("=" * width)
print(" RECEIPT ".center(width, "="))
print("Coffee".ljust(18) + "3.50".rjust(6))
print("=" * width)
Output
========================
======= 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

Pythoneditable
options = ["Start", "Settings", "Quit"]
for o in options:
    print("[" + o.center(10) + "]")
Output
[  Start   ]
[ Settings ]
[   Quit   ]

Common mistakes

Using more than one fill character

fillchar must be a single character, otherwise Python raises TypeError.

Pythoneditable
try:
    print("Hi".center(10, "-="))
except TypeError:
    print("TypeError: fillchar must be one character")
print("Hi".center(10, "-"))
Output
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).

Spotted a mistake on this page? Tell us