Python3 center()方法
center() 方法返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
语法
center()方法语法:
str.center(width[, fillchar])
参数
- width -- 字符串的总宽度。
- fillchar -- 填充字符。
返回值
返回一个指定的宽度 width 居中的字符串,如果 width 小于字符串宽度直接返回字符串,否则使用 fillchar 去填充。
实例
以下实例展示了center()方法的实例:
#!/usr/bin/python3
str = "[study.p2hp.com]"
print ("str.center(40, '*') : ", str.center(40, '*'))
以上实例输出结果如下:
str.center(40, '*') : ************[study.p2hp.com]************
Python3 字符串



好好学习天天向上
522***154@qq.com
str.center(width[, fillchar]) 函数:
1、如果 width 小于字符串宽度直接返回字符串,不会截断:
>>> str = "[study.p2hp.com]" >>> print ("str.center(4, '*') : ", str.center(4, '*')) str.center(4, '*') : [study.p2hp.com] // width 小于字符串宽度 >>>2、fillchar 默认是空格
>>> str = "[study.p2hp.com]" >>> print ("str.center(40) : ", str.center(40)) str.center(40) : [study.p2hp.com] // fillchar默认是空格3、fillchar 只能是单个字符
>>> str = "[study.p2hp.com]" >>> print ("str.center(40, '?!') : ", str.center(40, '?!')) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: The fill character must be exactly one character long好好学习天天向上
522***154@qq.com