字符串之center方法

center() 方法返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:AZ Ning


#center()方法语法:
str.center(width[, fillchar])

 

例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:AZ Ning
#center()方法语法:
# str.center(width[, fillchar])

str = "Azning"
print(str.center(40,"-"))

结果:

-----------------Azning-----------------

特别提醒:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:AZ Ning
#center()方法语法:
# str.center(width[, fillchar])
# 返回一个指定的宽度 width 居中的字符串,如果 width 小于字符串宽度直接返回字符串,否则使用 fillchar 去填充。

str = "Azning"
# print(str.center(40,"-"))

'''
    特别提醒
1、如果 width 小于字符串宽度直接返回字符串,不会截断:
2、fillchar 默认是空格
3、fillchar 只能是单个字符  

'''
print(" width 小于字符串宽度直接返回字符串,不会截断:",str.center(5,"-"))
print("fillchar默认是空格:",str.center(40))
print("fillchar只能是单个字符:",str.center(40,"*-"))

运行结果如下:

 width 小于字符串宽度直接返回字符串,不会截断: Azning
fillchar默认是空格:                  Azning                 
Traceback (most recent call last):
  File "F:/pythonxuexi/字符串之center方法.py", line 20, in <module>
    print("fillchar只能是单个字符:",str.center(40,"*-"))
TypeError: The fill character must be exactly one character long

 

posted @ 2018-05-12 15:35  Azning  阅读(600)  评论(0编辑  收藏  举报