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.
string.center(length, character)
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) |
The string.center()
method returns a string which is padded with the specified character, however it does not modify the original string.
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 24centered_string = sentence.center(24)print('The centered string is: ', centered_string)
Here we use both the length
and character
parameters.
sentence = 'I love Edpresso!'# lets use a length of 24 and ! as the charactercentered_string = sentence.center(24, '!')print('The centered string is: ', centered_string)