Python String center() Method
The str.center()
method center aligns the string by padding it with a specified character (fillchar
) that fills the string on both the left and right sides of the string and returns a new string.
Example:
# Python Center Method
text = "Python Programming"
print(text.center(25, "*"))
Output
****Python Programming***
Syntax
The Syntax of the str.center()
function is:
str.center(width[, fillchar])
Here, str
is a string.
Parameters
The str.center()
function can take two parameters.
- width - The length of the string after padding with the characters.
- fillchar (optional) - The character that needs to be used for padding. If
fillchar
parameter is not passed, the ASCII whitespace is used as the default argument.
Return Value
The str.center()
function returns a copy of padded string with specified fillchar
. It does not modify the original string.
Note: The original string is returned as-is if the given width
is less than the total length of the string.
Example 1: center() method with specific fillchar
In the below example, we have used the center()
method and passed various fillchar
characters. The center()
method returns the copy of the centered string padded with fillchar
at both ends.
# Python Center Method
text = "Python"
print(text.center(25, "#"))
print(text.center(25, "*"))
print(text.center(25, "$"))
print(text.center(25, "_"))
print(text.center(25, "-"))
print(text.center(25, "~"))
Output
##########Python#########
**********Python*********
$$$$$$$$$$Python$$$$$$$$$
__________Python_________
----------Python---------
~~~~~~~~~~Python~~~~~~~~~
Example 2: center() method with default fillchar
In the below example, we have not passed the fillchar
argument to the center()
method. Hence the center()
method pads with a default whitespace
character and returns the string with the padded length.
# Python Center Method Default Argument
text = "Python"
print(text.center(10))
print(text.center(15))
print(text.center(20))
print(text.center(25))
print(text.center(30))
Output
Python
Python
Python
Python
Python
Example 3: center() method that has a width less than the string length
If the width
passed to the center()
method is less than the length of the string, the center() method will return the original string as-is.
# Python Center Method
text = "Python"
print(text.center(2,"#"))
print(text.center(5, "*"))
Output
Python
Python
Reference: Python Official Docs