Reputation: 13
I'm trying to specify the number of digits (not decimal places) for a number output. Specifically, I'm trying to make the output be a three digit number. For example: If a user inputs the number 7, the output is then 007.
Upvotes: 1
Views: 188
Reputation: 23251
All submitted answers sorted by time:
>>> timeit(lambda: '%03d' % 7, number=100000)
0.010141897959158541
>>> timeit(lambda: '{:03}'.format(7), number=100000)
0.046049894736881924
>>> timeit(lambda: str(7).rjust(3, '0'), number=100000)
0.04794490118149497
>>> timeit(lambda: format(7, '03d'), number=100000)
0.053364350161117083
Upvotes: 0
Reputation: 23251
Rounding out all the options:
>>> i = 7
>>> '{:03}'.format(i)
'007'
Upvotes: 2