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 the Python string center Function with an example.

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

String_Value.center(Width, Char)
  • Width: Please specify the Justifying length of a string.
  • Char: This 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.

Python center String function Example

The following set of examples helps you understand the Python string center Function.

For Str2, it Justifies the String variable Str1 to the Center 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 Python 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 Str4 and Str5 variables.

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

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 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