Python center

The Python center() function is a simple and useful technique for justifying (aligning) a string to the center position within a given width. By default, this function fills the remaining width with specified characters (white spaces) and returns a new string. Here, the center() function evenly assigns the spaces on both the left and right sides of the original string.

In this section, we discuss how to write the Python string center function with an example. The center() function accepts two arguments and returns a new string. Remember, although the default padding character is a white space, we can use any single character.

Python string center Syntax

The string center function accepts only one character as a second argument, and the syntax is

String_Value.center(Width, Char)
  • String_Value:
  • Width: Please specify the justifying length of a string. The total number of blocks or spaces reserved to justify the text to the middle. It must be an integer value (both positive and negative).
  • Char: This padding character parameter is optional, and if you omit this argument, it considers the white spaces as a default parameter. To change the default value, please specify the characters you want to use or see in the remaining width.

Return Value: The center() function returns a completely new string with either the default white space padding or a designated character (the second arg).

NOTE: It does not alter the original string. So, we must save the result set in a completely new string.

Python String center with a default argument (spaces)

As we mentioned earlier in the syntax, the second argument is optional; its default value is a space. So, if we use the center() function without the second argument, it will add ASCII spaces to fill the gap.

In this example, we pad the ‘Hello’ message. Here, we used the center() function with a width argument (value of 11) and no char (second argument). As the width is 11, the center function must return a length of 11. As the Hello message is only five characters, the function must fill the remaining characters with spaces (default value). So, three empty characters + Hello + three spaces.

a = 'Hello'
b = a.center(11)
print(b)
   Hello   

Simple Math for padding: If we subtract the width value from the length of the original string, we get the padding value. For instance, 11 (width) – 5 (length of Hello) = 6. So, three spaces padded on the left and 3 on the right. If width = 10, left padding = 5//2  and remaining on the right.

Width Less than the Original

If you assign the width argument value less than the original string length, the Python center() function does not modify (shrink or trim) the original string. Instead, it simply returns the original string as an output. For example, although we set the width as 3, which is less than 5 (the length of Hello), the code below returns Hello as the output.

a = 'Hello'
b = a.center(3)
print(b)
Hello

Padding a String with a Special Character

In the previous two examples, we used the Python center() function with a single argument (width) and without the char. However, if you use the second argument, we can replace the spaces with the special character mentioned in the second argument. To demonstrate the same, we use a simple example.

Here, the width must be thirteen characters, and the center() function justifies the “Hello” word to the middle. Among those 13, 5 original characters (Hello), and the remaining characters are filled with the @ special character.

a = 'Hello'
b = a.center(13, '@')
print(b)
@@@@Hello@@@@

Python center function padding a string with a character

Instead of using a special character, we can use an alphabet or a number enclosed within a single quote. If we use an alphabet as the second character, the center() function justifies the given text to the middle and fills the remaining spaces with this alphabet.

a = 'Message'
b = a.center(20, 'T')
print(b)
TTTTTTMessageTTTTTTT

To use the number as the second argument, follow the technique mentioned below. Here, the center() function fills the spaces with 9.

a = 'Message'
b = a.center(15, '9')
print(b)
9999Message9999

Using multiple characters as a second argument

The Python center() function only accepts a single character as the second argument. If you use an inter or multiple characters (String), it will throw an error.

a = 'Hello'
b = a.center(11, 'AB')
print(b)

Error Message

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

If you replace (b = a.center(11, ‘AB’)) ‘AB’ with 1 (b = a.center(11, 1)), it will throw the below error.

TypeError: The fill character must be a Unicode character, not int.

Python center String Function Example

The following set of examples helps you understand the string center function. For Str2, it justifies the String variable Str1 to the centre and fills the remaining width with default white spaces, and prints the output.

You may be confused with empty spaces; that’s why we used ‘=’ as the second parameter. This Python Str3 statement fills the remaining width with the ‘=’ symbol.

The center function returns the output in the new string instead of altering the original. To change the original, write the following statement.

Str1 = Str1.center()

This String Method only allows a single character as the second argument. Let us see what happens when we use the two characters, i.e., + and *, in the Str4 and Str5 variables.

As you see from the image below, it is throwing an error saying: ‘TypeError: The fill character must be exactly one character long’.

Str2 = Str1.center(30)
print('Justify the string with White spaces is =', Str2)

Str3 = Str1.center(30, '=')
print("Justify the string with '=' using this is =", Str3)

# Observe the Original
print('Converted String is =', Str1.center(30, '='))
print('Original String is =', Str1)

# Performing it directly
Str4 = 'Tutorial Gateway'.center(30, '*')
print("Justify the string with '*' using it is =", Str4)

# Performing it with two characters
Str5 = 'Tutorial Gateway'.center(30, '+*')
print("Justify the string with '+' and '*' using it is =",Str5)
Python string center function Example

Practical Example

The following example uses the Python center() function to print the pyramid pattern of stars.

num = 10
for i in range(1, num, 2):
row ='*'*i
print(row.center(num))
    *     
   ***    
  *****   
 *******  
********* 

Working with the Table report

If you are displaying a report in a table format, center-aligning each column value (including the header) is the most standard task. In the following Python center() function example, we will pad the report title into the middle. Next, we will display the table with all information aligned in the middle.

-----------------Employee Information----------------
       ID       |       Name      |       City      | 
       1        |       John      |     New York    | 
       2        |      Tracy      |   Los Angeles   | 
       3        |       Mike      |     Chicago     | 
       4        |        Xi       |   Philadelphia  |