What is a string.center in Python?

The center method returns a new string of a passed length. In the returned string, the source string is centered and the fill character is padded at the start and end of the string.

Syntax

string.center(width[, fillchar])

Parameters

  • width: the resulting string length.

  • fillchar: the fill character to be added at the start and end of the string. It is an optional value. By default, space will be added.

Return value

  • If the width is greater than the length of the string, then the specified fill character will be added at the start and end of the string to make the string length equal to the passed width value.

  • If the width is lesser than the length of the string, then the original string is returned.

The padding will be done by adding one fill character in the end and adding one to the start. This continues until the length of string meets the passed width.

Code

string = "123"
print(string.center(4, '$'))
print(string.center(5, '*'))
print(string.center(6, '#'))
print(string.center(1, '#'))

In the code above, we created a 123 string and:

  • Called the center method with width of 4 and fillchar . In this case, the string length is 3 and the width is 4. 4 is greater than 3 and 4 - 3 = 1, so one is added to the end of the string and 123$ is returned.

  • Called the center method with width of 5 and fillchar *. In this case, the string length is 3 and the width is 5. 5 is greater than 3, and 5 - 3 = 2, so one * is added to the end of the string, then one * is added to the beginning of the string, and *123* is returned.

  • Called the center method with width of 6 and fillchar #. In this case, the string length is 3 and the width is 6. 6 is greater than 3 and 6 - 3 = 3, so one # is added to the end and one # is added to the start. One # is again added to the end, and then the string and #123## are returned.

  • Called center method with width of 1 and fillchar #. In this case, the string length is 3 and the width is 1. 1 is smaller than 3, so the string and 123 will be returned.

Free Resources