给定一个字符串和一个整数。操作是,将整数附加到4个零的字符串,并获取结果字符串的最后4个字符。以下两种方法中的哪一种在优化和可读性方面是更好的方法?如果还有其他任何建议我的话。
result_str = ("0000" + str(integer_value))[-4:]
或
result_str = "%04d" % integer_value
0< = integer_value< = 999
答案 0 :(得分:2)
我更喜欢str.format(),它比使用%
>>> '{0:0>4}'.format(8)
'0008'
答案 1 :(得分:1)
>>> some_number = 8
>>> str(some_number).zfill(4)
'0008'
zfill会自动将前导零添加到字符串的前面,将整个字符串转换为该字符串
>>> 'pie'.zfill(4)
'0pie'
>>> ':)'.zfill(5)
'000:)'
答案 2 :(得分:1)
使用timeit
确定哪种版本对您的Python版本最有效。
以下是您的方法和其他答案中提出的其他方法的计时结果示例:
$ python
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> s1 = "(\"0000\" + str(123))[-4:]"
>>> timeit.timeit(stmt=s1, number=1000000)
0.26563405990600586
>>> s2 = "\"%04d\" % 123"
>>> timeit.timeit(stmt=s2, number=1000000)
0.021093130111694336
>>> s3 = "str(123).zfill(4)"
>>> timeit.timeit(stmt=s3, number=1000000)
0.3430290222167969
>>> s4 = "'{0:0>4}'.format(123)"
>>> timeit.timeit(stmt=s4, number=1000000)
0.3574531078338623
这表明在建议的选项中,以下内容最快:
result_str = "%04d" % integer_value
10倍加速是微不足道的还是非平凡的,可能取决于你的用例。
从可读性的角度来看,考虑到C和Perl的经验,最后一个选项是我最熟悉的。我会发现这比任何其他更具体的Python选项更具可读性。