Python formatting from 1 to 01

I want to be able to format the date / time input for my function.

I currently have a function that basically adds 0 to a number if it only has 1 digit.

def format_num(str(num)):
    if len(num) < 2:
        return "0" + num
    return num

      

I was wondering if there is a more pythonic way to do this.

+3


source to share


4 answers


You can use the string method zfill

to fill strings with zeros to a specified width. Specify width 2:

>>> '1'.zfill(2)
'01'

      



Strings longer than one character will not be affected:

>>> '31'.zfill(2)
'31'

      

+4


source


>>> ["{:02}".format(num) for num in (1,22,333)]
['01', '22', '333']

      



For more information about syntax, understands the method format

, see. Https://docs.python.org/2/library/string.html#formatspec .

+4


source


Calling string format functions is several times slower than

>>> "%02d" % 8
'08'
>>> "%02d" % 80
'80'

      

Therefore, if you care about performance, try to avoid function calls.

python -m timeit "'%02d' % 8"
100000000 loops, best of 3: 0.0166 usec per loop

python -m timeit "'8'.zfill(2)"
10000000 loops, best of 3: 0.163 usec per loop

python -m timeit "'{:02}'.format(2)"
1000000 loops, best of 3: 0.385 usec per loop

      

In such simple and often referred to code, I would take a faster solution.

+3


source


To answer your direct question -

You can format your number like this:

format(num, '02d')

      

Example:

nums = [1,22,333]

for num in nums:
    print format(num, '02d')

      

Outputs:

01
22
333

      

However, you say that you are using date and time. You can format the datetime object directly

%d - Zero padded day
%m - Zero padded month

      

+2


source







All Articles