string center() in Python

In this article, we would cover string center() method in Python. The method center() is mainly use to center the string in such a way that padding is done both the sides. We use a fill character for the padding. If we don’t pass the fill character, it leaves the space empty.

Padding is mainly done to generate space around the supplied string. The syntax of the center() method in Python –

str.center(width[, fillchar])

It is worth mentioning here that, the original string would be returned if the width is less than length of the string. Next, we understand the above concepts with relevant examples.

string center() in Python

Example I. Let’s say, we don’t provide a padding character. In this case, the default padding character will be empty space, as we have already mentioned.

x = "Hello World!"
fd = x.center(25)
print(fd)

It would return with –

       Hello World!

What we did here? We took a string “Hello World!” and stored it in variable x. Then, we use center() method to center align the string with empty space as fill character. Since, the length of the string is 12. Therefore, it leaves seven empty spaces on the left side and six empty spaces on the right side.

If, in case you want to know the length of string then use len() method. Here, the string was stored in variable x, so to find the length –

len(x)

It returns with –

12

Example II. Continuing with the above example. What if we chose to provide the width which is less than the length of string –

x = "Hello World!"
fd = x.center(5)
print(fd)

It would return with –

Hello World!

The above result is self-explanatory. The original string returns if width is less than the length of the string i.e. 5 < 12.

Example III. This time around, we use a padding character “$” –

x = "Hello World!"
fd = x.center(25, "$")
print(fd)

It returns with –

$$$$$$$Hello World!$$$$$$

As already discussed in first example, the length of the string is 12. Rest 13 spaces would filled by “$” – 7 on the left side and 6 on the right.

In conclusion, we have discussed string center() method in Python here.