如何将零填充到字符串? [英] How to pad zeroes to a string?
本文介绍了如何将零填充到字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用Python的方法将数字字符串填充到左侧为零的方式是什么,即数字字符串具有特定的长度?
What is a Pythonic way to pad a numeric string with zeroes to the left, i.e. so the numeric string has a specific length?
推荐答案
字符串:
>>> n = '4'
>>> print(n.zfill(3))
004
对于数字:
>>> n = 4
>>> print(f'{n:03}') # Preferred method, python >= 3.6
004
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n)) # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n)) # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n)) # python >= 2.7 + python3
004
这篇关于如何将零填充到字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文