如何在数字字符串的左边加上零,使字符串具有特定的长度?
当前回答
我添加了如何使用f-string中字符串长度的int,因为它似乎没有被覆盖:
>>> pad_number = len("this_string")
11
>>> s = f"{1:0{pad_number}}" }
>>> s
'00000000001'
其他回答
要填充字符串:
>>> 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
字符串格式文档。
我添加了如何使用f-string中字符串长度的int,因为它似乎没有被覆盖:
>>> pad_number = len("this_string")
11
>>> s = f"{1:0{pad_number}}" }
>>> s
'00000000001'
>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'
如果你想要相反的:
>>> '99'.ljust(5,'0')
'99000'
使用Python>=3.6时,最干净的方法是将f-string与字符串格式一起使用:
>>> s = f"{1:08}" # inline with int
>>> s
'00000001'
>>> s = f"{'1':0>8}" # inline with str
>>> s
'00000001'
>>> n = 1
>>> s = f"{n:08}" # int variable
>>> s
'00000001'
>>> c = "1"
>>> s = f"{c:0>8}" # str variable
>>> s
'00000001'
我更喜欢使用int格式,因为只有这样符号才能正确处理:
>>> f"{-1:08}"
'-0000001'
>>> f"{1:+08}"
'+0000001'
>>> f"{'-1':0>8}"
'000000-1'
如果您希望填充一个整数,同时限制有效数字(使用f字符串):
a = 4.432
>> 4.432
a = f'{a:04.1f}'
>> '04.4'
f“{a:04.1f}”这转换为1个十进制/(浮点)点,将数字向左填充,直到总共4个字符。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- Printf与std::字符串?
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if