Python String center() Method (original) (raw)
Last Updated : 28 Apr, 2025
**center() method in Python is a simple and efficient way to center-align strings within a given width. By default, it uses spaces to fill the extra space but can also be customized to use any character we want. **Example:
[GFGTABS]
Python
``
`s1 = "hello" s2 = s1.center(20)
print(s2)
`
``
[/GFGTABS]
**Explanation: Here, the word “hello” is centered within a 20-character wide space, with spaces padded on both sides.
**Syntax of string center()
string.center(length[, fillchar])
**Parameters:
- **length: length of the string after padding with the characters.
- **fillchar: (optional) characters which need to be padded. If it’s not provided, space is taken as the default argument.
**Returns: It returns a string padded with specified fillchar and it doesn’t modify the original string.
Examples of string center() parameter
**Example 1: The center() method allows you to customize the character used to fill the padding by passing the fillchar argument. This is useful when formatting text with visual markers like dashes (-) or asterisks (*).
[GFGTABS]
Python
``
`a = "hello" b = a.center(20, '-')
print(b)
`
``
[/GFGTABS]
Output
-------hello--------
**Explanation: Here, the string “hello” is centered within 20 characters using dashes (-) as the padding character.
**Example 2: If the width specified in the center() method is smaller than the length of the original string, Python will not change the string. It will simply return the original string without any centering.
[GFGTABS]
Python
``
`a = "hello" b = a.center(3)
print(b)
`
``
[/GFGTABS]
**Explanation: In this case, since the width (3) is less than the string length (5), no padding is applied.
**Example 3: center() is often used to format headers in console-based tables, making them more readable and visually distinct.
[GFGTABS]
Python
``
`h1 = "Name" h2 = "Age" h3 = "Location"
s1 = h1.center(20, '-') s2 = h2.center(20, '-') s3 = h3.center(20, '-')
print(s1) print(s2) print(s3)
`
``
[/GFGTABS]
Output
--------Name-------- --------Age--------- ------Location------
**Explanation: Here, the headers are centered and the extra space is filled with dashes (-). This gives the headers a clean and organized look when printed.