Python String center() Method With Example

Python String center

Now, we are going to learn about the center method. This method returns a centered string with the length of the given width. The padding is done with the specified character, which is given as an argument. Let’s have a look at a simple example, which would demonstrate the same thing.

Python String center() Method

As you can see in the above program, we have a string, and then we are trying to call the center method. We have provided two arguments for the center method. The first one is the width, which is going to be the length of the string with the padded characters. The another is the padding character. This argument is optional, and if not provided, the default one is considered as whitespace.

Let’s have a look at the output now, which would demonstrate the return value from the center method.

—-GyaniPandit—–

As you can see, we got a centered string, with a length of 20, and the padding is done with the specified character, which is a ‘-‘ in this case. If the padding character is not specified,  it defaults to the whitespace. The center method returns a string, and the original string is not modified. Let’s have a look at another example, where we would not give the padding character.

As you can see in the above program, we have not given the padding character this time, so, it defaults to the whitespace. Let’s have a look at the output again, which gives a clearer idea about the output.

The return value from the center method:     GyaniPandit

As you can see, we got a centered string, with the padding done. So, as and when required, you can make use of the center method. Remember that the center method returns a centered string, and the padding is done with the specified padding character. If the padding character is not given as an argument to the center method, it defaults to whitespace.