Center() method - string class

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:

sampleString = "Be yourself"

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

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

 

sampleString = "Have Fun"

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

 

Output:

Be yourself#

#Be yourself#

#Have Fun

 


Copyright 2024 © pythontic.com