The Python center function aligns a string centrally by adding padding on both the left and right sides of the string. This method accepts two arguments: the first is the desired width, while the second, which is optional, is the fillchar. The fillchar defines the character that will be employed to fill the padding on either side 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
In this section, we will explore multiple examples to illustrate the usage of the string center method in Python.
Python String Center Method Example 1: default fill char
In this instance, we did not provide a second argument. By default, it assumes spaces.
# Python center() function example
# Variable declaration
str = "Hello World"
# Calling function
str2 = str.center(20)
# Displaying result
print("Old value:", str)
print("New value:", str2)
Output:
Old value: Hello World
New value: Hello World
Python String Center Method Example 2
In this instance, we are supplying the padding character (which is optional) as #. Refer to the example provided.
# Python center() function example
# Variable declaration
str = "Hello World"
# Calling function
str2 = str.center(20,'#')
# Displaying result
print("Old value:", str)
print("New value:", str2)
Output:
Old value: Hello World
New value: ##Hello World##
Python String Center Method Example 3
Let us consider an additional example to illustrate the usage of the string center method in Python.
# Python center() function example
# Variable declaration
str = "Hello World"
if str == "Hell0 ExampleTech":
str2 = str.center(20,'#')
else:
str2 = str.center(20,'!')
# Displaying result
print("Old value:", str)
print("New value:", str2)
Output:
Old value: Hello World
New value: !!Hello World!!