Python String center() Method

The center() method returns a new centered string of the specified length, which is padded with the specified character. The deafult character is space.

Syntax:

str.center(width, fillchar)

Parameters:

  1. width : The total length of the string.
  2. fillchar :(Optional) A character to be used for padding.

Return Value:

Returns a string.

Center String with Fill Char

The following example demonstrates the center() method.

Example: str.center()
greet='Hi'
print(greet.center(4, '-'))
print(greet.center(5, '*'))
print(greet.center(6, '>'))
Output
'-Hi-'
'**Hi*'
'>>Hi>>'

In the above example, greet.center(4, '-') specified total length of the new string is 4, and fillchar is -. So, it returns '-Hi-' string where Hi is centered and padded with - char and total length is 4. It starts padding from the beginning.

Center String with the Default Fill Char

The default fill character is a space, as shown below.

Example: center() with default fillchar
greet = 'Hi'
print(greet.center(3))
print(greet.center(4))
Output
' Hi'
' Hi '

The length of the fillchar parameter should be 1. If it is greater than 1 then the center() method will throw a Type Error.

Example: center() throws error
greet = 'Hello'
print(greet.center(10, '##'))
Output
Traceback (most recent call last)
    File "<pyshell#18>", line 1, in <module>
        print(greet.center(10, '##'))
TypeError: The fill character must be exactly one character long

If the length of the string is greater than the specified width then the original string is returned without any padding.

Example: center()
mystr = 'Python is a programming language'
print(mystr.center(20, '-'))

mystr = 'Hello World'
print(mystr.center(2,'*'))
Output
Python is a programming language
Hello World

The center() method will throw a TypeError if the width is not specified.

Example:
greet = 'Hi'
print(greet.center())
Output
Traceback (most recent call last)
    File "<pyshell#18>", line 1, in <module>
        print(greet.center())
TypeError: center() takes at least 1 argument (0 given)
Want to check how much you know Python?