使用'n'位数的Python字符串格式(使用键时)Python 2.7

时间:2017-11-27 02:37:36

标签: python string-formatting

要在字符串格式中使用特定的位数,我知道可以这样做:

In [18]: hours = 01

In [19]: "%.2d" %(hours)
Out[19]: '01'

In [20]: "%.2f" %(hours)
Out[20]: '1.00'

但我的情况有点不同。我使用特定键来表示值,例如:

for filename in os.listdir('/home/user/zphot_01/')

我希望'01'有不同的值,即

for filename in os.listdir('/home/user/zphot_{value1}/'.format(value1=some_number):

当我将上述方法与some_number = 01一起使用时,它不会考虑0,因此无法识别我的文件夹。

修改

大多数答案只针对一个值,但是,我希望有一个以上的键值,即:

for filename in os.listdir('/home/user/zphot_{value1}/zphot_{value2}'.format(value1=some_number1,value2=some_number2)). 

3 个答案:

答案 0 :(得分:3)

new format string syntax允许您使用格式说明符,就像旧的基于%的语法一样。您可以使用的格式说明符是相似的,在所有情况下都不完全相同(我认为),但据我所知,使用旧语法可以使用旧语法完成任何操作。

您所要做的就是将格式说明符放在格式化表达式中,用冒号分隔字段名称/数字。在这种情况下,您可以使用{value1:02d},其中02d是获取整数的零填充(0)宽度-2(2)表示的代码( d)。

答案 1 :(得分:1)

print("{0:02}".format(1))
>>0001

刚从其他答案和评论员那里了解到我们不需要zfill,但可以使用表达式:02来提供填充。

扩展到更多职位

print("{0:02}_{1:02}".format(1, 2))
>>0001_0002

答案 2 :(得分:1)

有很多方法。看this answer

这是我的主观意见,但我已经将它们命令为最差的。

>>> '1'.zfill(2)
'01'
>>> '%02d' % 1
'01'
>>> '%02s' % '1'
'01'
>>> '{0:0>2}'.format(1)
'01'
>>> '{0:02d}'.format(1)
'01'
>>> '{:02d}'.format(1)
'01'
>>> f'{1:02}'
'01'

然后,你必须将它与你当前的字符串结合起来,没有什么比这更复杂了。

编辑:

我不确定OP究竟对他的编辑提出了什么要求,但是:

for filename in os.listdir('/home/user/zphot_{value1}/zphot_{value2}'.format(value1=some_number1,value2=some_number2)).

可以通过很多方式改变,我会给出一些例子:

>>> number_first, number_second = '1', '2'
>>> '/home/user/zphot_{value1}/zphot_{value2}'.format(value1 = number_first.zfill(2), value2 = '2'.zfill(2))
'/home/user/zphot_01/zphot_02'
>>> '/home/user/zphot_{}/zphot_{}'.format('1'.zfill(2), number_second.zfill(2))
'/home/user/zphot_01/zphot_02'
>>> f'/home/user/zphot_{{number_first:02}}/zphot_{2:02}'
'/home/user/zphot_01/zphot_02'    
>>> '/home/user/zphot_%02d/zphot_%02s' % (1, '2')
'/home/user/zphot_01/zphot_02'
>>> '/home/user/zphot_{:02d}/zphot_{:02d}'.format(1, 2)
'/home/user/zphot_01/zphot_02'