Reputation: 186
Given a string and an integer. Operations is, append integer to string of 4 zeros and get the last 4 characters of the result string. which one of the below two approaches is a better approach in terms of optimisation and readability for this? If there exits any other suggest me that as well.
result_str = ("0000" + str(integer_value))[-4:]
or
result_str = "%04d" % integer_value
0 <= integer_value <=999
Upvotes: 0
Views: 78
Reputation: 96947
Use timeit
to figure which is most efficient for your version of Python.
Here's an example of timing results for your methods and other methods proposed in other answers:
$ 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
This suggests that the following works fastest among the suggested options:
result_str = "%04d" % integer_value
Whether a 10-fold speedup is trivial or non-trivial will likely depend on your use case.
From a readability standpoint, this last option is the most familiar to me, given experience with C and Perl. I would find this more readable than any of the other more Python-specific options.
Upvotes: 1
Reputation: 23064
I prefer str.format() which is more flexible than string formatting with %
>>> '{0:0>4}'.format(8)
'0008'
Upvotes: 2
Reputation: 3217
>>> some_number = 8
>>> str(some_number).zfill(4)
'0008'
zfill automatically adds leading zeros to the front of a string, turning the entire string into that long
>>> 'pie'.zfill(4)
'0pie'
>>> ':)'.zfill(5)
'000:)'
Upvotes: 1