Python center

Python center function is used to Justify the string to the Center. And fill the remaining width with specified character (By Default white spaces) and returns the new string. In this section, we discuss how to write center Function in Python Programming with example.

Python center Syntax

The string center Function in Python accepts only one Character as a function second argument. The syntax of the Python center function is

String_Value.center(Width, Char)
  • String_Value: A valid String literal.
  • Width: Please specify the Justifying length of a string.
  • Char: This parameter is optional, and if you Omit this, center Function considers the white spaces as a default parameter. To change the default value, please specify the Characters you want to use in the remaining width.

Python center method Example

The following set of examples help you understand the center Function.

# Python Center Method Example

Str1 = 'Tutorial Gateway'

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

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

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

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

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

It Justify the String variable Str1 to the Center and fill the remaining width with default white spaces using the center function and prints the output

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

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

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

The Python center function returns the output in the new string, instead of altering the original string.

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

As you see, the original string Str1 is unchanged. If you want to change the original String, then you can write the following statement

Str1 = Str1.center()

The center String Method only allows a single character as the second argument. Let us see what happen when we use two characters (+ and *)

Str5 = 'Tutorial Gateway'.center(30, '+*')
print("Justify the string with '+' and '*' using Center() is =",Str5)

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