python实现指定字符串补全空格、前面填充0的方法

yipeiwu_com6年前Python基础

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 "

总结

以上所述是小编给大家介绍的python实现指定字符串补全空格、前面填充0的方法  ,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

探寻python多线程ctrl+c退出问题解决方案

场景: 经常会遇到下述问题:很多io busy的应用采取多线程的方式来解决,但这时候会发现python命令行不响应ctrl-c 了,而对应的java代码则没有问题: 复制代码 代码如下:...

python批量处理文件或文件夹

本文实例为大家分享了python批量处理文件或文件夹的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- import os,shutil impor...

用python画一只可爱的皮卡丘实例

用python画一只可爱的皮卡丘实例

效果图 #!/usr/bin/env python # -*- coding:utf-8 -*- from turtle import * ''' 绘制皮卡丘头部 ''' de...

Python按行读取文件的简单实现方法

1:readline() file = open("sample.txt") while 1: line = file.readline() if not line:...

对pandas中iloc,loc取数据差别及按条件取值的方法详解

Dataframe使用loc取某几行几列的数据: print(df.loc[0:4,['item_price_level','item_sales_level','item_coll...