str.center
Center the string, padding it to the length width.
Python 3.13
str.center(width[, fillchar])Parameters
- widthint
- The length of the result.
- fillcharstroptional
- The padding character, a space by default; exactly one character.
Return value
A new string; the original is not changed.
Examples
Centering with spaces
Python 3.13
print('[' + 'hi'.center(6) + ']')[ hi ]
A heading with asterisks
Python 3.13
print('Menu'.center(12, '*'))****Menu****
Details
If the string is already at least width long, it is returned unchanged. In f-strings, the {text:^10} format does the same.
