Python String center() Method

Example

Print the word "banana", occupy 20 characters, and center-align "banana":

txt = "banana"
x = txt.center(20)
print(x)

Run Instance

Definition and Usage

The center() method uses the specified character (default is space) as the padding character to center-align the string.

Syntax

string.center(length, character)

Parameter Value

Parameter Description
length Required. The length of the returned string.
character Optional. Characters used to fill the missing spaces on both sides. The default is " " (space).

More Examples

Example

Use the letter "O" as the padding character:

txt = "banana"
x = txt.center(20, "O")
print(x)

Run Instance