The original implementation of str.center was added here, in 1990:
# Center a string
def center(s, width):
n = len(s)
if n >= width: return s
return ' '*((width-n)/2) + s + ' '*(width -(width-n)/2)
It was changed a year later, in 1991, to
# Center a string
def center(s, width):
"""center(s, width) -> string
Return a center version of s, in a field of the specified
width. padded with spaces as needed. The string is never
truncated.
"""
n = width - len(s)
if n <= 0: return s
half = n/2
if n%2 and width%2:
# This ensures that center(center(s, i), j) = center(s, j)
half = half+1
return ' '*half + s + ' '*(n-half)
and the current C implementation found here does
static PyObject *
stringlib_center_impl(PyObject *self, Py_ssize_t width, char fillchar)
/*[clinic end generated code: output=d8da2e055288b4c2 input=3776fd278765d89b]*/
{
Py_ssize_t marg, left;
if (STRINGLIB_LEN(self) >= width) {
return return_self(self);
}
marg = width - STRINGLIB_LEN(self);
left = marg / 2 + (marg & width & 1);
return pad(self, left, marg - left, fillchar);
}
I suspect the "why" for the current implementation is the
This ensures that center(center(s, i), j) = center(s, j)
comment, but you'd have to ask Guido for confirmation.