Python String center() method
The center() method will center align the string, using a specified character (space is default) as the fill character.
Syntax
1 2 3 |
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
1 2 3 4 5 6 7 8 9 |
# 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
1 2 3 4 5 |
String value: Hello World After the center() method: !!!!!!!!!!!!!!Hello World!!!!!!!!!!!!!!! |
Example 2
1 2 3 4 5 6 7 8 9 10 |
# 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
1 2 3 4 |
Actual String: Hello World After padding the String: Hello World |
Example 3
1 2 3 4 5 6 7 8 9 |
# 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
1 2 3 |
After padding String is: **TutorialsandExamples** |