python .center用法_Python Pandas Series.str.center()用法及代码示例
Series.str可用于以字符串形式訪問系列的值并對其應用幾種方法。 Pandas Series.str.center()函數(shù)用于在系列/索引中的字符串的左側(cè)和右側(cè)填充其他字符。該功能等效于Python的str.center()。
用法: Series.str.center(width, fillchar=’ ‘)
參數(shù):
width:產(chǎn)生的字符串的最小寬度;其他字符將用fillchar填充
fillchar:填充字符,默認為空白
返回:填充
范例1:采用Series.str.center()函數(shù)用“ *”符號填充給定系列對象的基礎數(shù)據(jù)中字符串的左側(cè)和右側(cè)。
# 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)
輸出:
現(xiàn)在我們將使用Series.str.center()函數(shù)在字符串的左側(cè)和右側(cè)填充“ *”符號。
# fill '*' in the left and right side of string
result = sr.str.center(width = 13, fillchar = '*')
# print the result
print(result)
輸出:
正如我們在輸出中看到的,Series.str.center()函數(shù)已成功在給定系列對象的基礎數(shù)據(jù)中的字符串的左側(cè)和右側(cè)填充了“ *”符號。
范例2:采用Series.str.center()函數(shù)用“ *”符號填充給定系列對象的基礎數(shù)據(jù)中字符串的左側(cè)和右側(cè)。
# 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)
輸出:
現(xiàn)在我們將使用Series.str.center()函數(shù)在字符串的左側(cè)和右側(cè)填充“ *”符號。
# 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)
輸出:
正如我們在輸出中看到的,Series.str.center()函數(shù)已成功在給定系列對象的基礎數(shù)據(jù)中的字符串的左側(cè)和右側(cè)填充了“ *”符號。
注意:如果width的值小于實際字符串的長度,則整個字符串將被打印而不會被截斷。
總結(jié)
以上是生活随笔為你收集整理的python .center用法_Python Pandas Series.str.center()用法及代码示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何使用动软代码生成器连接oracle生
- 下一篇: Python 开发的 10 个小贴士,你