Published Oct 26, 2023
Contribute to Docs

The .center() string method returns a new string that has been amended with padding. The padding is allocated evenly to both sides of the string, depending on the overall length specified. The default padding is whitespace, but any character may be used, including numbers or symbols.


string.center(length, 'character')

The length parameter is required and must be an integer. This will be the length of new string. The .center() method accepts an optional 'character' parameter. If no character is specified the default is whitespace.


In the following example the .center() method is used to create a string that has a length of 10 characters. The padding character is a ‘+’:

str = "Hello"
new_str = str.center(11, '+')

The above example will show the following output:


Codebyte Example

The below example shows what happens when the length parameter specified in the .center() method isn’t long enough to create a new padded string. The new string is unchanged, as the length of the original string is less than that of the specified one in the length parameter.

Visit us
Hide code
Hide output
Hide output

All contributors

Looking to contribute?

Learn Python on Codecademy