Tutorial Study Image

Python center()

The center() function in python helps to make the string as center align. Along with this function, we can specify the width of the string including the padded character, and which character need to fill in the missing place.


string.center(width[, fillchar]) #where width is an integer number
 

center() Parameters:

The center() function takes two parameters. If the argument 'fillchar' is missing it will take space(" ") as default. The padding is done at both left and right.

Parameter Description Required / Optional
width the length of the returned string Required
fillchar padding character optional

center() Return Value

The method returns a string aligned at the center with specified width and padded with a given fill character. It doesn't modify the original string.

Input Return Value
if arguments Returns a string 

Examples of center() method in Python

Example 1: python center() method with default fillchar


string = "How are you?"

updated_string = string.center(24)

print("Centered String is: ", updated_string )
 

Output:


Centered String is:     How are you?    

Example 2:Python center() method with * fillchar


string = "How are you?"

updated_string = string.center(24, '*')

print("Centered String is: ", updated_string )
 

Output:


Centered String is:  ***How are you?****