1. 程式人生 > >字符串之center方法

字符串之center方法

.py PE 提醒 單個字符 char file 使用 fill back

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

字符串之center方法