Python String center() Method
The center()
method is used to center-align a string within a specified width by padding it with a specified fill character (default is space).
Syntax
string.center(width, fillchar)
Parameters
width
(required): The total length of the resulting string after centering.
fillchar
(optional): The character to fill the padding (default is space).
Return Value
Returns a new string with the original string centered and padded with fill character on both sides if needed. The original string is not modified.
If the width
is less than or equal to the length of the original string, the original string is returned without any padding.
Examples
Center a String
text = "apple"
result = text.center(20)
print(result)
print(f"{result}is very sweet")
Output:
apple
apple is very sweet
In this example, the text
variable has "apple"
string which has 5
characters.
Therefore, text.center(20)
creates a new string of total length 20
characters and the orginal string "apple"
is placed in the center.
The rest (20-5=15 characters) is filled with spaces.
- Left padding: 7 spaces
- Right padding: 8 spaces (If the extra padding is odd, the right side gets the extra space).
Using a Custom Fill Character
text = "apple"
result = text.center(10, "-")
print(result) # Output: --apple---
When Width is Less Than or Equal to String Length
If the specified width is less than or equal to the length of the original string, the original string is returned without any changes.
text = "apple"
result = text.center(3, "-")
print(result) # Output: apple