str.center()
Center a string in a fixed-width field — a copy is returned; the original is unchanged. Never truncates.
Demo
center pads the original on BOTH sides until the total length equals `width`. When the padding is odd, the extra character goes on the LEFT (e.g. "hi".center(5) → " hi "). If the string is already at or past `width`, the original is returned unchanged — center never truncates. fillchar must be exactly one character; empty falls back to the default space.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| width | int | yes | Target minimum length. Shorter strings are padded; longer or equal ones are returned unchanged. |
| fillchar | str | no (" ") | Single-character string used for padding. Multi-char or empty raises TypeError. |
Return value
str — A copy of the string centered in a field of at least `width` characters, padded on both sides with `fillchar`. If odd padding is needed, the extra character goes on the LEFT.
Common patterns
print(" README ".center(60, "="))
header = "".join(col.center(12) for col in columns)
print(name.ljust(20) + status.center(10) + count.rjust(6))
Examples
Pitfalls
"hi".center(5)
right = (width - len(s)) // 2 left = width - len(s) - right
"long text".center(3)
s[:width].center(width)
"hi".center(10, "-=")
"hi".center(10, "-")
s = "hi" s.center(10) print(s)
s = s.center(10) print(s)
When to use
- Centered labels in text UIs and CLI banners
- Tabular output where visual center matters
- Padding-only-if-needed workflows
- Rendering fixed-width report columns
- Numeric columns → rjust reads better for right-aligned numbers
- Left-aligned columns → ljust
- You need to truncate too → slice first, then center
- You need padding on one side only → ljust or rjust
Notes
FAQ
CPython uses floor(padding / 2) on the right and ceil(padding / 2) on the left. This makes center() deterministic — Python has consistently biased extra padding toward the left since the method was introduced.