Python | Pandas Series.str.center()
Last Updated :
27 Mar, 2019
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 whitespace
Returns : 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.
import pandas as pd
sr = pd.Series([ 'New_York' , 'Lisbon' , 'Tokyo' , 'Paris' , 'Munich' ])
idx = [ 'City 1' , 'City 2' , 'City 3' , 'City 4' , 'City 5' ]
sr.index = idx
print (sr)
|
Output :
Now we will use Series.str.center()
function to fill ‘*’ symbol in the left and right side of the string.
result = sr. str .center(width = 13 , fillchar = '*' )
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.
import pandas as pd
sr = pd.Series([ 'Mike' , 'Alessa' , 'Nick' , 'Kim' , 'Britney' ])
idx = [ 'Name 1' , 'Name 2' , 'Name 3' , 'Name 4' , 'Name 5' ]
sr.index = idx
print (sr)
|
Output :
Now we will use Series.str.center()
function to fill ‘*’ symbol in the left and right side of the string.
result = sr. str .center(width = 5 , fillchar = '*' )
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...