如何在数字字符串的左边加上零,使字符串具有特定的长度?
当前回答
除了zfill,您还可以使用常规字符串格式:
print(f'{number:05d}') # (since Python 3.6), or
print('{:05d}'.format(number)) # or
print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)
print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, '05d'))
字符串格式和f-string的文档。
其他回答
也可以:
h = 2
m = 7
s = 3
print("%02d:%02d:%02d" % (h, m, s))
因此输出将为:“02:07:03”
>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'
如果你想要相反的:
>>> '99'.ljust(5,'0')
'99000'
要填充字符串:
>>> 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
字符串格式文档。
您也可以重复“0”,将其前置到str(n)并获得最右侧的宽度切片。又快又脏的小表情。
def pad_left(n, width, pad="0"):
return ((pad * width) + str(n))[-width:]
对于那些来这里理解而不仅仅是快速回答的人来说。我特别针对时间字符串:
hour = 4
minute = 3
"{:0>2}:{:0>2}".format(hour,minute)
# prints 04:03
"{:0>3}:{:0>5}".format(hour,minute)
# prints '004:00003'
"{:0<3}:{:0<5}".format(hour,minute)
# prints '400:30000'
"{:$<3}:{:#<5}".format(hour,minute)
# prints '4$$:3####'
“0”符号替换为“2”填充字符,默认值为空白“>”符号表示字符串左侧的所有2“0”字符“:”符号format_spec
推荐文章
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 我如何在c++中创建一个随机的字母数字字符串?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 如何使用JavaScript大写字符串中每个单词的第一个字母?
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?