Python String center()

Filed Under: Python

Python string center() function returns a centered string of specified size. We can also specify the character to use for padding, the default is whitespace.

Python String center()

The function syntax is:


str.center(width[, fillchar])

Let’s look at some examples of using string center() method.


s = 'Hello'

s1 = s.center(20)
print(f'***{s1}***')

Output: *** Hello ***

Note that my source string size is 5 and the new string size is 20. So both side paddings can’t be of equal size, here 7 whitespace characters are padded before the source string and 8 whitespace characters are padded after the source string.

NOTE: If you are not familiar with f-prefixed string formatting, it’s a new formatting method introduced in Python 3.6. You can read more about it in python f-strings article.

What will happen if the string size is more than the specified width? Let’s find it out with a simple example.


>>> s = 'Hello World'
>>> s.center(6)
'Hello World'
>>> s.center(12)
'Hello World '
>>> s.center(11)
'Hello World'
>>> 

So if the string size is more than the specified width, the original string is returned without any padding or removing any characters.

Python String center() with fillchar


s = 'Hello'

s1 = s.center(20, '#')
print(f'***{s1}***')

s1 = s.center(20, 'ç')
print(f'***{s1}***')

python string center

Before we conclude this post, let’s look at some error scenarios.


s.center('#')

Output: TypeError: 'str' object cannot be interpreted as an integer

The error occurred because we didn’t provide the length of the output string.


s1 = s.center()

Output: TypeError: center() takes at least 1 argument (0 given)


s.center(20, '#$')

Output: TypeError: The fill character must be exactly one character long

That’s all for python string center() method. We can use it to create a new string of specific size with source string centered. It’s useful in creating a string to display purpose in UI or in HTML reports.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: API Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages