What is the string.center() method in Python?

The string.center() method is simply used to return a new string centered at a specified length and also padded with the specified character. In this method, the space is the default character.

Syntax

string.center(length, character)

Parameters

Parameter Description
length This is required. It helps return the length of the new string
character This is optional. It is the character that will fill the missing space on each side of the new string (space is the default character)

Return value

The string.center() method returns a string which is padded with the specified character, however it does not modify the original string.

Code

Example 1

Let’s use the string.center() method with just the length parameter to return a centered string.

sentence = 'I love Edpresso!'
# lets use a length of 24
centered_string = sentence.center(24)
print('The centered string is: ', centered_string)

Example 2

Here we use both the length and character parameters.

sentence = 'I love Edpresso!'
# lets use a length of 24 and ! as the character
centered_string = sentence.center(24, '!')
print('The centered string is: ', centered_string)

Free Resources