Viperwoman
Viperwoman

Reputation: 13

Specifying digits (without decimal) in Python

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

Answers (5)

mhlester
mhlester

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

mhlester
mhlester

Reputation: 23251

Rounding out all the options:

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

Upvotes: 2

ooga
ooga

Reputation: 15511

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

Upvotes: 5

Guy Gavriely
Guy Gavriely

Reputation: 11396

>>> i = 7
>>> '%03d' % i
'007'

Upvotes: 4

mhlester
mhlester

Reputation: 23251

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

rjust docs

Upvotes: 2

Related Questions