python3.4學習筆記(二十一) python實現指定字符串補全空格、前面填充0的方法
Python zfill()方法返回指定長度的字符串,原字符串右對齊,前面填充0。
zfill()方法語法:str.zfill(width)
參數width -- 指定字符串的長度。原字符串右對齊,前面填充0。
返回指定長度的字符串。
以下實例展示了 zfill()函數的使用方法:
#!/usr/bin/python
str = "this is string example....wow!!!";
print str.zfill(40);
print str.zfill(50);
以上實例輸出結果如下:
00000000this is string example....wow!!!
000000000000000000this is string example....wow!!!
zfill()則用於向數值的字符串表達式左側填充0, 該函數可以正確理解正負號:
>>> '12'.zfill(5)
'00012’
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
=====================================
在Python中打印字符串時可以調用ljust(左對齊),rjust(右對齊),center(中間對齊)來輸出整齊美觀的字符串
python實現指定字符串補全空格的方法:
如果希望字符串的長度固定,給定的字符串又不夠長度,我們可以通過rjust,ljust和center三個方法來給字符串補全空格
rjust,向右對其,在左邊補空格
s = "123".rjust(5) assert s == " 123"
ljust,向左對其,在右邊補空格
s = "123".ljust(5) assert s == "123 "
center,讓字符串居中,在左右補空格
s = "123".center(5) assert s == " 123 "