Python String center() method
Python String center() method
The center() method will center align the string, using a specified character (space is default) as the fill character.
Syntax
string.center(width[, fillchar])
Parameter
width This parameter represents the length of the returned string.
fillchar This parameter represents the character to fill the missing space on each side and the default value is " " (space).
Return
This method returns centered in a string of length width.
Example 1
# Python String program explaining
# the center() method
str = "Hello World";
print("String value:",str)
# centering the string with length 40 and fillchar '!'.
print("After the center() method:")
print ( str.center(40, '!'))
Output
String value: Hello World After the center() method: !!!!!!!!!!!!!!Hello World!!!!!!!!!!!!!!!
Example 2
# Python String program explaining
# the center() method
str = "Hello World"
print("Actual String: ",str)
# the defalt fillchar passed is ' '.
newStr = str.center(24)
# here filchar not provided so takes space by default.
print ("After padding the String: ", newStr)
Output
Actual String: Hello World After padding the String: Hello World
Example 3
# Python String program explaining
# the center() method
# passing the string to centralize
str = "TutorialsandExamples"
new_str = str.center(24, '*')
# here fillchar is provided
print ("After padding String is:", new_str)
Output
After padding String is: **TutorialsandExamples**
