Python center() method alligns string to the center by filling paddings left and right of the string. This method takes two parameters, first is a width and second is a fillchar which is optional. The fillchar is a character which is used to fill left and right padding of the string.
Python String center() Method
It has the following syntax:
center(width[,fillchar])
Parameters
- width (required)
- fillchar (optional)
Return Type
It returns modified string.
Different Examples for Python String center() Method
Here, we are going to take several examples to demonstrate the string center() Method in Python.
Python String Center() Method Example 1: default fill char
Here, we did not pass second parameter. By default it takes spaces.
# Python center() function example
# Variable declaration
str = "Hello Pythonapp"
# Calling function
str2 = str.center(20)
# Displaying result
print("Old value:", str)
print("New value:", str2)
Output:
Old value: Hello Pythonapp
New value: Hello Pythonapp
Python String Center() Method Example 2
Here, we are providing padding char (optional) parameter as #. See the example.
# Python center() function example
# Variable declaration
str = "Hello Pythonapp"
# Calling function
str2 = str.center(20,'#')
# Displaying result
print("Old value:", str)
print("New value:", str2)
Output:
Old value: Hello Pythonapp
New value: ##Hello Pythonapp##
Python String Center() Method Example 3
Let us take another example to demonstrate the string center() method in Python.
# Python center() function example
# Variable declaration
str = "Hello PythonApp"
if str == "Hell0 PythonApp":
str2 = str.center(20,'#')
else:
str2 = str.center(20,'!')
# Displaying result
print("Old value:", str)
print("New value:", str2)
Output:
Old value: Hello PythonApp
New value: !!Hello PythonApp!!