Python String center() Method
The Python String center() method returns a string centered at the specified width, and fillchar is the fill character, which defaults to a space.
Python String center() Syntax
The center() method syntax.
str.center(width[, fillchar])
Python String center() Parameters
Parameter | Description |
---|---|
|
The total width of the string. |
fillchar |
The character to fill in. |
Python String center() Return Value
Returns a string centered at the specified width, if width is less than the string width, otherwise fillchar is used to fill the string.
Python String center() Example#1
The following example shows an instance of the center() method.
#!/usr/bin/python3
str = "[apidemos]"
print ("str.center(40, '*') : ", str.center(40, '*'))
Output:
Python String center() Example#2
center() method, with #
as the fill character.
#!/usr/bin/python3
string = "welcome to apidemos.com"
new_string = string.center(24, '#')
# here fillchar is provided
print("After padding String is:", new_string)
Output:
Python String center() Example#3
The value of the length parameter of the center() method is less than the length of the original string.
#!/usr/bin/python3
string = "apidemos,apimdemos"
# new string will be unchanged
print(string.center(5))
Output:
In the above example, the new string is unchanged because the length of the original string (18) exceeds the length value provided by the center method (5). Therefore, the new string returned is unchanged.