Python Tutorial Python Advanced Python References Python Libraries

Python String - center() Method



The Python center() method returns the string with specified length and padded from left and right. This method has one optional parameter to specify padding character. Default value of this parameter is whitespace.

If the specified length is less than the length of the string, no padding is done.

Syntax

string.center(length, character)

Parameters

length Required. specify length of string after padding.
character Optional. specify padding character. default value is whitespace.

Return Value

Returns the string with specified length and padded from left and right applied on a given string.

Example:

In the example below, center() method is to return the string with specified length and padded from left and right. If the specified length is less than the length of the string, no padding is done.

MyString = "Hello World!"
print(MyString.center(20))

MyString = "HelloWorld!"
print(MyString.center(20, "@"))

The output of the above code will be:

    Hello World!  
@@@@HelloWorld!@@@@@

❮ Python String Methods

5