In this tutorial, we’ll learn how to properly use Python string center() method with the help of easy Python code examples.
Introduction: Python String center() Method
This method is used to return a string with padded characters or with some whitespace if no character is specified.
Syntax of center() Method
string.center( widthOfString, character(optional) )
- You can see that Python string center() method takes two arguments.
- First one specifies the length of string with padded characters.
- Second parameter is optional. It can be used to specify which character should be padded to string. If not specified then it will use whitespaces.
- This center() method returns a string having characters padded to it(left and right).
Example 1: Applying center() Method to Python String
name='Zeeshan' print( name.center(16,'*') )
Output
****Zeeshan*****
First argument will specify the length of new string with padded characters. You can increase/decrease the length of returned string.
Let’s try it with different length and characters. See below example:
name='Zeeshan' print(name.center(16,'*')) print(name.center(10,'$')) print(name.center(20,'_')) print(name.center(8,'*'))
Output
****Zeeshan***** $Zeeshan$$ ______Zeeshan_______ Zeeshan*
As you can see in the last output line, character starts adding from right to left, means first character will be added to right then second one will be added to left then third one again to the right and so on until the length is covered.
Example 2: When Length is less than String
name='Zeeshan Ali' print(name.center(6,'*'))
Output
Zeeshan
As you can see here that only actual string will be returned with no padded characters/whitespaces when the length is less than the actual string.
Example 3: When Character is not Specified
name=’Zeeshan’
print(name.center(20))
Output
Zeeshan
Python string center() method will assign whitespaces when the character is not specified.
Example 4: Passing multiple Characters to center() Method
name='Zeeshan' print(name.center(20,'**'))
Output
TypeError: The fill character must be exactly one character long
Passing multiple characters to Python string center() method will raise a type error exception. So just pass a single character or don’t specify it if you want it to have whitespaces by default.
Example 5: center() Method Return Value
originalValue='Yasir' returnedValue=originalValue.center(10,'-') print(returnedValue) print(originalValue)
Output
--Yasir--- Yasir
As you can see in the above output that no changes has been made to the original string. Python string center() method returns a new string with characters padded to it(if specified or else whitespaces will be padded by default).
Conclusion
As a conclusion of this tutorial, now you have a detailed practical knowledge of how to properly use Python string center method. I’ll be looking forward to have your valuable feedback on this post. Thank you for reading it.