The center()
method in Python is used to center-align a string within a specified width. It pads the string with a specified character (default is space) on both sides to achieve the desired width.
Here's the syntax of the center()
method:
string.center(width, fillchar)
width
: The total width of the centered string, including the original string and any padding characters.fillchar
(optional): The character used for padding. It is optional, and if not provided, the method will use a space character as the default.
# Example string
original_string = "Hello, world!"
# Using the center() method to center the string within a width of 20 characters
centered_string = original_string.center(20)
print("Original String:", original_string)
print("Centered String:", centered_string)
Original String: Hello, world!
Centered String: Hello, world!
In this example, the original string "Hello, world!" is centered within a width of 20 characters. The method added spaces on both sides to make the total width 20 characters, resulting in a centered string. If you want to use a different padding character, you can pass it as the second argument to the center()
method. For instance, using centered_string = original_string.center(20, '*')
would center the string with asterisks (*) as padding characters.