Python String center()

The center() method returns a new centered string after padding it with the specified character.

Example


center() Syntax

The syntax of the center() method is:

str.center(width, [fillchar])

Here, str is a string.


center() Parameters

The center() method takes two parameters:

  • width - length of the string with padded characters
  • fillchar (optional) - padding character

Note: If fillchar is not provided, whitespace is taken as the default argument.


center() Return Value

The center() method returns:

  • a string padded with specified fillchar

Note: The center() method doesn't modify the original string.


Example 1: Python center()

Output

 $Python is awesome$$

In the above example, we have used the center() method with the sentence string as sentence.center(20,'$').

The method returns a new centered string after padding the sentence with '$' up to length 20.


Example 2: center() with Default Argument

Output

Centered String:     Python is awesome   

Here, we have not passed the fillchar parameter in the center() method. The method pads whitespace to text making the length of the centered string 24.