Question

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.

Was it helpful?

Solution 3

>>> i = 7
>>> str(i).rjust(3, '0')
'007'

rjust docs

OTHER TIPS

>>> n = 7
>>> print format(n, '03d')
007
>>> i = 7
>>> '%03d' % i
'007'

Rounding out all the options:

>>> i = 7
>>> '{:03}'.format(i)
'007'

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top