Python String center() Function
The String center() method returns a new string that is centered within a string of the specified length, using a specified character as the fill character.
The original string is returned as it is, if width parameter is less than or equal to string length.
Syntax
my_string.center(width, fillchar)
center() Parameters
Python String center() function parameters:
| Parameter | Condition | Description |
|---|---|---|
width | Required | The length of the string |
fillchar | Optional | A character you want to use as a fill character. Default value is an ASCII space. |
If fillchar is not provided, a whitespace is taken as the default argument.
center() Return Value
Python String center() function returns a new string centered within a string of the specified length, using the specified fill character.
Examples
Example 1: Center a String using center() method
By default, the string is padded with whitespace (ASCII space, ).
my_str = 'Centered'
result = my_str.center(12)
print(f"'{result}'") # Output: ' Centered '
output
' Centered '
Example 2: Center a String with Custom Padding
You can modify the padding character by specifying a fill character.
For example, center a string with * as a fill character
my_str = 'Centered'
result = my_str.center(12, '*')
print(f"'{result}'") # Output: '**Centered**'
output
'**Centered**'
Example 3: Center a String with too small width
If the width is less than or equal to string length, then the original string is returned.
my_str = 'Centered'
result = my_str.center(4, '*')
print(f"'{result}'") # Output: 'Centered'
output
'Centered'
Equivalent Method to Center a String
You can center a string as you would do with center() method by using format() method.
For example, using the center() method:
my_str = 'Centered'
result = my_str.center(12, '*')
print(result) # Output: **Centered**
output
**Centered**
This is equivalent to the use of format() method:
my_str = 'Centered'
result = '{:*^12}'.format(my_str)
print(result) # Output: **Centered**
output
**Centered**