Series.str
can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.center()
function is used for filling left and right side of strings in the Series/Index with an additional character. The function is equivalent to Python’s str.center()
.
Syntax: Series.str.center(width, fillchar=’ ‘)
Parameter :
width : Minimum width of resulting string; additional characters will be filled with fillchar
fillchar : Additional character for filling, default is whitespaceReturns : filled
Example #1: Use Series.str.center()
function to fill the left and right side of the string in the underlying data of the given series object by ‘*’ symbol.
# importing pandas as pd import pandas as pd # Creating the Series sr = pd.Series([ 'New_York' , 'Lisbon' , 'Tokyo' , 'Paris' , 'Munich' ]) # Creating the index idx = [ 'City 1' , 'City 2' , 'City 3' , 'City 4' , 'City 5' ] # set the index sr.index = idx # Print the series print (sr) |
Output :
Now we will use Series.str.center()
function to fill ‘*’ symbol in the left and right side of the string.
# fill '*' in the left and right side of string result = sr. str .center(width = 13 , fillchar = '*' ) # print the result print (result) |
Output :
As we can see in the output, the Series.str.center()
function has successfully filled ‘*’ symbol in the left and the right side of the string in the underlying data of the given series object.
Example #2 : Use Series.str.center()
function to fill the left and right side of the string in the underlying data of the given series object by ‘*’ symbol.
# importing pandas as pd import pandas as pd # Creating the Series sr = pd.Series([ 'Mike' , 'Alessa' , 'Nick' , 'Kim' , 'Britney' ]) # Creating the index idx = [ 'Name 1' , 'Name 2' , 'Name 3' , 'Name 4' , 'Name 5' ] # set the index sr.index = idx # Print the series print (sr) |
Output :
Now we will use Series.str.center()
function to fill ‘*’ symbol in the left and right side of the string.
# fill '*' in the left and right side of string # width after filling should be 5 result = sr. str .center(width = 5 , fillchar = '*' ) # print the result print (result) |
Output :
As we can see in the output, the Series.str.center()
function has successfully filled ‘*’ symbol in the left and the right side of the string in the underlying data of the given series object.
Note : If the value of width is smaller than the length of actual string then the whole string is printed without truncating it.