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
str.rjust
Returns the string right-justified in a field of the given width, padded on the left with fillchar. Returns the original string unchanged if it is already at least width characters long.
str.zfill
Returns a copy padded on the left with '0' digits to reach the given width. Unlike rjust('0'), it preserves a leading sign ('+' or '-') by placing the zeros after it.
str.format
Substitutes replacement fields delimited by { } in the string with values from args and kwargs, using the Format Specification Mini-Language. In modern Python, f-strings are usually preferred for literals; str.format() remains ideal for templates loaded at runtime.
str.strip
Returns a copy of the string with leading and trailing whitespace removed. If chars is given, removes any leading/trailing characters that appear in the chars set (not a prefix/suffix — it is a character set).
str.lstrip
Returns a copy of the string with leading characters removed. Defaults to whitespace; a chars argument specifies a set of characters to strip from the left.