Python Pandas Series.str.center()

Python Pandas Series.str.center()

Series.str可以用来将系列的值作为字符串访问,并对其应用几种方法。Pandas Series.str.center()函数用于为系列/索引中的字符串的左右两边填充一个额外的字符。该函数等同于Python的str.center()。

语法:

Series.str.center(width, fillchar=’ ‘)

参数:
width :产生的字符串的最小宽度;额外的字符将用fillchar填充。
fillchar :用于填充的附加字符,默认为空白。

返回 : 填充

示例#1:使用Series.str.center()函数在给定的系列对象的底层数据中用’*’符号填充字符串的左边和右边。

# 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)

输出 :

Python Pandas Series.str.center()

现在我们将使用Series.str.center()函数在字符串的左边和右边填充’*’符号。

# fill '*' in the left and right side of string
result = sr.str.center(width = 13, fillchar = '*')
  
# print the result
print(result)

输出 :

Python Pandas Series.str.center()

正如我们在输出中看到的,Series.str.center()函数已经成功地在给定系列对象的底层数据中的字符串左侧和右侧填充了’*’符号。

示例#2 :使用Series.str.center()函数在给定的系列对象的基础数据中用’*’符号填充字符串的左边和右边。

# 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)

输出 :

Python Pandas Series.str.center()

现在我们将使用Series.str.center()函数在字符串的左边和右边填充’*’符号。

# 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)

输出 :

Python Pandas Series.str.center()

正如我们在输出中看到的,Series.str.center()函数已经成功地在给定系列对象的基础数据中的字符串的左边和右边填充了’*’符号。

注意:如果宽度的值小于实际字符串的长度,那么整个字符串将被打印出来,而不会被截断。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程