The center Method in Python: Centering a String

Center a string by padding it on the left and right to a specified length with a specified character.

center(width[, fillchar])

  • width -- desired minimum length of the resulting string
  • fillchar -- character to pad the string with; defaults to a space

The original string is not truncated, even if it is shorter than the specified length.

''.center(3, 'w')  # 'www'
'1'.center(2, 'w')  # '1w'
'1'.center(4, 'w')  # 'w1ww'
'1'.center(0, 'w')  # '1'
'1'.center(4)  # ' 1  '

Characters are added cyclically, first on the right, then on the left. To position the string to the right, use rjust(). To position it to the left, use ljust().