Python string center() method

The Python string center() method returns a centre-justified new string based on a specified width. It allows the optional parameter to provide the padding characters to the left and right of the string. The space character is the default filler.

Syntax:

String_var.center(length[, fillchar])

This center() method accepts two parameters.

length The length of the new string to be returned
fillchar(optional) The padding to the left and right of the newly formed string.
Return Value:

A new string of length is provided that centres the specified string with padding to the left and right with spaces or characters specified as the second parameter.

			

# Python example of the center() method, with the only first parameter.

website = "Tutorials Nation"
print(website.center(20))  


				

Output:

Tutorials Nation
			

<p>The above example pads two default space characters on each side of the string "Tutorials Nation" to make the entire length of the string twenty.</p>

<div class="code-view">
		<pre>
			<code class="language-python">
<xmp>
# Python example of the center() method, with the second parameter, is provided.
website = "tutorials nation"
print(website.center(20, '*'))  

				

Output:

**Tutorials Nation**

The above example pads two asterisks (*) characters on each side of the string "Tutorials Nation" to make the entire length of the string twenty.

			

website = "tutorials nation"
print(website.center(10)  

				

Output:

Tutorials Nation

If the specified width is less than the string's length, Python returns the original string. In the above example, the string is not changed and returns its exact copy.