Skip to main content

center()

The center() method is a string method in Python that returns a centered string within a specified width. It pads the original string with spaces on both sides to center it within the specified width. The method takes one argument, which is the width of the centered string. If the width is smaller than the original string, the original string is returned unchanged.

Parameter Values

Parameter Description
width

The total width of the centered string including the original string.

Return Values

The center() method from string methods always returns a str type.

How to Use center() in Python

Example 1:

The center() method returns a centered string of a specified length by padding the original string with a specified character (whitespace by default) on both sides.

'hello'.center(10) # Output: '  hello   '
Example 2:

The center() method can accept a second argument to specify the padding character.

'python'.center(15, '=') # Output: '====python===='
Example 3:

If the specified length is smaller than the length of the original string, the center() method returns the original string unchanged.

'programming'.center(5) # Output: 'programming'