Python String center() method returns a new string, centered by padding it with the specified character(default is space) until it reaches a given width.
Syntax
string.center(width, fillchar)
Parameters
- width(required): length of the string with padded characters.
- fillchar(optional): The character to fill the padding. The default is a space.
Return value
It returns a new string padded with specified fillchar.
In the case of the odd-length string, the extra padding will be placed on the right.
Visual Representation
Example 1: How to Use String center() Method
name ='krunal'
centered_string = name.center(10)
print(centered_string)
Output
krunal
Example 2: Passing fillchar argument
name ='krunal'
centered_string = name.center(12,'*')
print(centered_string)
Output
***krunal***
Example 3: Width argument value less than the original string’s length
name ='krunal'
print(name.center(4,'*'))
Output
krunal
It returns the original string because the width is 4, which is less than the string’s length of 5.