In this article, we are going to learn about the Python string center() method. Python string center function is used to pad a string with a specified character.
In the previous tutorial, we have seen the Python string casefold() method to convert string to case folded string.
Headings of Contents
Python String center() Method
The Python String center() method is a string built-in method that will only use with string.
Python string center() method is used to align the string to the center by filling the padding to the left and right of the string.
Syntax:
The syntax of python string center() method is:
string.center(length, character)
Parameter:
The string center function in python take two argument:
length:- Required, The length of the returned string.
Character:- Optional, The character to fill the missing space on each side. Default is space (” “).
Return Type:
The Python string center() method return the string which is padded with specified character.
Let’s see an example for using Python center() string method.
Python string center() Method Example:
Here we will take various example to understand the Python string center function.
Example 1:
Here we will use string center() method without passing second character.
str = "PROGRAMMING"
print("Old string:- ", str)
str2 = str.center(20)
print("New string:- ",str2)
Output
Old string:- PROGRAMMING
New string:- PROGRAMMING
Example 2:
Here we will use python string center() on the string mystr with second parameter ‘#‘.
mystr = "PyThOn"
print("Old string:- ", mystr)
mystr2 = mystr.center(20, '#')
print("New string:- ",mystr2)
Output
Old string:- PyThOn
New string:- #######PyThOn#######
Example 3
Here we will use the python string center() method on the string mystr with second parameter ‘*‘.
mystr = "Python"
print("Old string:- ", mystr)
mystr2 = mystr.center(16, '*')
print("New string:- ",mystr2)
Output
Old string:- Python
New string:- *****Python*****
Conclusion:
In this tutorial, you have learned the Python string center() method to center the string with a specified character.
I hope this string center function in Python tutorial will help you, if you like this article, please comment and share with your friends who want to learn Python programming from scratch to advance.
For More Information:- Click Here