formatting

str.center

Returns the string centered in a field of the given width, padded on both sides with fillchar. When padding is uneven, the extra pad placement depends on the parity of width and margin — for the common odd-width case, it lands on the LEFT.

str.center(width[, fillchar])

Parameters

Parameter Purpose
width minimum total width
fillchar single character used to pad (default ' ')

Examples

>>> 'hi'.center(6)
'  hi  '

even padding

'hi'.center(7, '-')

'---hi--' — 5 pad chars split 3 left / 2 right (CPython puts the extra on the LEFT when width is odd)

>>> 'title'.center(20, '=')
'=======title========'

common for banner-style headers

>>> 'hello'.center(3)
'hello'

not truncated when already wide enough

Gotcha

When width - len(s) is odd, the extra pad character goes on the LEFT (not the right) — CPython uses left = marg // 2 + (marg & width & 1). So 'hi'.center(7, '-') is '---hi--', not '--hi---'. Test with your actual values.

Related methods

← All Python string methods · Python built-ins