center() String Method in Python with Examples

center() method centers given string in a given number of character space.

center() String Method Syntax

center(self, width, fillchar=' ', /)

center() Syntax Explanation

center() method returns a centered string of length of given width.

Padding is done using the specified fill character (fillchar) (default is a space).

Argument self is string itself.

Example: center() String Method


message = 'Welcome to Python!'
print(message.center(40))

Output

           Welcome to Python!           

Explanation: Here number of character space (width) given is 40 so string 'Welcome to Python!' is in center of 40 characters space. Here default character for padding is space.

To understand more clearly, now we use another argument i.e. fill character. See example below:

Example:


message = 'Welcome to Python!'
print(message.center(40,'-))

Output

 -----------Welcome to Python!-----------        

Note: if specified width is less than string length then this method has no any effect.



Related String Methods