center() method - string class

center() method of string class in Python places the original string, in a string of specified width. Both sides of new string will have padded characters.

Str Updated 9 Mar 2017 1 min read

Method Name

center

Method signature

center(width[, fillchar])

Method Overview

  • The center() method of str class does not return the central character or any central part of the string.

  • On a string with “n” as width, center() will make the original string appear in the center portion.

  • Remaining portion of the string will be padded with specified padding character as per the fillchar parameters.

  • If no fillchar is specified space character is used as the padding character.

  • When the specified width is an even number the padding starts at the right side of the original string.

  • When the specified width is an odd number the padding starts at the left side of the original string.

  • If the specified width is smaller than then the length of the string than a replica copy of the original string is returned.

Example

python
sampleString = "Be yourself"

print(sampleString.center(12,"#"))

print(sampleString.center(13,"#"))

sampleString = "Have Fun"

print(sampleString.center(9,"#"))

Output

Output
Be yourself#

#Be yourself#

#Have Fun