Python center() method alligns string to the center by filling paddings left and right of the string. This method takes two parameters, first is a width and second is a fillchar which is optional. The fillchar is a character which is used to fill left and right padding of the string.
It has the following syntax:
It returns modified string.
Here, we are going to take several examples to demonstrate the string center() Method in Python.
Here, we did not pass second parameter. By default it takes spaces.
Output:
Old value: Hello Tpointtech New value: Hello Tpointtech
The following example demonstrates how the Python center() function places a string in the center of a specified width using a custom fill character.
Output:
Old value: Hello Tpointtech New value: ##Hello Tpointtech##
The following example demonstrates how the Python center() function can be used with an if-else condition to center a string using different fill characters based on a specified condition.
Output:
Old value: Hello Tpointtech New value: !!Hello Tpointtech!!
We request you to subscribe our newsletter for upcoming updates.