Python string Method - center()

https://w‮i.ww‬giftidea.com

The center() method in Python strings returns a copy of the string centered within a specified width. The width is specified as an argument to the center() method, and any extra space is filled with a specified character.

The syntax for the center() method is as follows:

string.center(width, fillchar)

Here, string is the string that we want to center, width is the width of the centered string, and fillchar is the character used to fill any extra space. If fillchar is not specified, a space character ' ' is used by default.

Example:

# Defining a string
my_string = "hello"

# Using the center() method
result_string = my_string.center(10, '*')

print(result_string)   # Output: "**hello**"

In the above example, the center() method is used to center the string my_string within a width of 10 characters, with the extra space filled with the '*' character. Since the length of my_string is 5, the extra space is 5 characters, which is split into 2 characters before and after my_string. The resulting string is stored in result_string and printed using the print() function. Note that the original string my_string is not modified by the center() method, since strings in Python are immutable.