Python String center() Method
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:
# Center the string 'hello' within a width of 20
s1 = "hello"
s2 = s1.center(20)
# Print the result
print(s2)
Output
hello
Table of Content
Syntax
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
- Returns a string padded with specified fillchar and it doesn’t modify the original string.
Using fillchar Parameter
The center() method also allows us to specify a character to fill the empty spaces instead of spaces. This can be useful if we want to use another symbol like a dash (-) or an asterisk (*) for alignment.
# Center the string 'hello' with dashes
a = "hello"
b = a.center(20, '-')
# Print the result
print(b)
Output
-------hello--------
Example: Handling Width Smaller than String Length
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.
# String 'hello' with width 3 (smaller than the length of the string)
a = "hello"
b = a.center(3)
# Print the result
print(b)
Output
hello
Example: Creating Header for Table
When printing a table or a list of data, we might want to center-align the headers to make them stand out. This is a common use case for the center() method.
# Table headers
h1 = "Name"
h2 = "Age"
h3 = "Location"
# Center each header within a width of 20 characters
s1 = h1.center(20, '-')
s2 = h2.center(20, '-')
s3 = h3.center(20, '-')
# Print the headers
print(s1)
print(s2)
print(s3)
Output
--------Name-------- --------Age--------- ------Location------
- Here, the headers are centered and the extra space is filled with dashes (-). This gives the headers a clean and organized look when printed.