python字符串-居中(center)


center方法使用填充字符對字符串進行填充,保持原字符串居中,默認填充字符是空格。

語法

center(width, fillchar=' ', /)

參數

  • width: 字符串的總長度。
  • fillchar: 填充字符,默認為空格。

返回值

  • 原字符串居中,長度為width的新字符串。

示例

str = 'abc'
# 注意前后使用空格填充
print('填充字符串到長度為5:', str.center(5))
print('填充字符串到長度為5,使用"*"號填充:', str.center(5, '*'))
# 原字符串長度為奇數,優先填充右邊;原字符串長度為偶數,優先填充左邊。
print('填充字符串到長度為4,優先填充右邊:', str.center(4, '*'))
print('填充字符串到長度為5,優先填充左邊:', 'abcd'.center(5, '*'))
print('填充字符串到長度為2,比原字符串長度小,字符串不變:', str.center(2, '*'))
填充字符串到長度為5:  abc 
填充字符串到長度為5,使用"*"號填充: *abc*
填充字符串到長度為4,優先填充右邊: abc*
填充字符串到長度為5,優先填充左邊: *abcd
填充字符串到長度為2,比原字符串長度小,字符串不變: abc

help()

Help on built-in function center:

center(width, fillchar=' ', /) method of builtins.str instance
    Return a centered string of length width.
    
    Padding is done using the specified fill character (default is a space).


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM