center() method in Python
The center() method returns a string which is center align with the specified character(space is default).
Syntax
string.center(length, character)
Parameters
- length - (Required) Length of the returned string.
- character - (Optional) The character used to fill in both sides instead of the blank space. If it's not given, space as default character.
The following example shows, how to use the center() method in python.
Example 1 : With default fill character (space)
txt1="Hi" txt2="Hello" txt3="Welcome" print(txt1.center(20)) print(txt2.center(20)) print(txt3.center(20))
Output
Hi Hello Welcome
Example 2 :
Print Following Pyramid Pattern using center() method in python.
* *** ***** ******* *********
n=10 for i in range(1,n,2): line='*'*i print(line.center(n))
Output
* *** ***** ******* *********
Example 3 :
Print Following Pattern using center() method in python.
********** **** **** *** *** ** ** * *
n=10 for i in range(0,n,2): line=' '*i print(line.center(n,"*"))
Output
********** **** **** *** *** ** ** * *