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:
- width : The total length of the string.
- 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.
greet='Hi'
print(greet.center(4, '-'))
print(greet.center(5, '*'))
print(greet.center(6, '>'))
'-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.
greet = 'Hi'
print(greet.center(3))
print(greet.center(4))
' 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
.
greet = 'Hello'
print(greet.center(10, '##'))
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.
mystr = 'Python is a programming language'
print(mystr.center(20, '-'))
mystr = 'Hello World'
print(mystr.center(2,'*'))
Python is a programming language
Hello World
The center()
method will throw a TypeError
if the width is not specified.
greet = 'Hi'
print(greet.center())
Traceback (most recent call last)
File "<pyshell#18>", line 1, in <module>
print(greet.center())
TypeError: center() takes at least 1 argument (0 given)