Python字符串中心() 方法
Python String center()方法创建并返回一个用指定字符填充的新字符串。
Syntax:
string.center(length[, fillchar])
Parameters:
- length: length of the string after padding with the characters.
- fillchar: (optional) characters which need to be padded. If it’s not provided, space is taken as the default argument.
Returns:
Returns a string padded with specified fillchar and it doesn’t modify the original string.
示例 1:使用默认 fillchar 的 center() 方法
Python
# 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
Python
# 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
示例 2:使用 #fillchar 的 center() 方法
Python
# 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#####