當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python string center()用法及代碼示例


center()方法創建並返回一個用指定字符填充的新字符串。

用法:

string.center(length[, fillchar])
參數:
length:length of the string after padding with the characters.
fillchar:(optional) characters which needs to be padded. 
If it's not provided, space is taken as default argument.
返回:
returns a string padded with specified fillchar and it doesn't modify 
the original string.

代碼1


# Python program to illustrate 
# string center() in python 
string = "geeks for geeks"
  
new_string = string.center(24) 
  
# here filchar not provided so takes space by default. 
print "After padding String is:", new_string

輸出:

After padding String is:     geeks for geeks

代碼2

# Python program to illustrate 
# string center() in python 
string = "geeks for geeks"
  
new_string = string.center(24, '*') 
  
# here fillchar is provided 
print "After padding String is:", new_string

輸出:

After padding String is:****geeks for geeks*****


相關用法


注:本文由純淨天空篩選整理自pawan_asipu大神的英文原創作品 string center() in python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。