1.zfill的功能
1)为字符串定义长度,如不满足长度,缺少的部分用0补齐。
比如,有个字符串abc,这个字符串的长度是3,现在想让这个字符串的长度变成10,不足的部分会用0来替代。
也就是说,这个abc会加上7个0。
2.zfill的用法
![a2a8d56f9c7e788ccc843e4104c687ad.png](https://img-blog.csdnimg.cn/img_convert/a2a8d56f9c7e788ccc843e4104c687ad.png)
string就是要被处理的字符串。字符串调用它的内置函数,通过.zfill(width)
调用。
()内的width是要传进去的参数。width代表希望新的字符串的长度是多少。
zfill会拿到原始的字符串,并且结合width长度,对字符串进行处理,生成一个新的字符串。会将它返回给新的变量newstr。
name = 'xiaobian'
new_name = name.zfill(10)
print(new_name)
运行结果: 00xiaobian
3.zfill的注意事项
1)与字符串的字符无关(任何字符都可以)。
2)如果定义长度小于或等于当前字符串长度,则不发生变化。
test_str = 'my name is xiaobian'
new_str = test_str.zfill(5)
print(new_str)
运行结果: my name is xiaobian
4.代码
# coding:utf-8
heart = 'love'
if __name__ == '__main__':
print(' t '+heart)
print('t '+heart)
print(heart.zfill(10))
print(heart.zfill(9))
print(heart.zfill(8))
print(heart.zfill(6))
print(heart.zfill(4))
运行结果:
/Users/llq/PycharmProjects/pythonlearn/pythonlearn/.venv/bin/python /Users/llq/PycharmProjects/pythonlearn/pythonlearn1/zfill.py
t love
t love
000000love
00000love
0000love
00love
love
进程已结束,退出代码为 0