Best way to format integer as string with leading zeros?

PythonString Formatting

Python Problem Overview


I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:

function add_nulls($int, $cnt=2) {
    $int = intval($int);
    for($i=0; $i<($cnt-strlen($int)); $i++)
        $nulls .= '0';
    return $nulls.$int;
}

Is there a function that can do this?

Python Solutions


Solution 1 - Python

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'

Solution 2 - Python

The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.

To output a string of length 5:


... in Python 3.5 and above: f-strings.

i = random.randint(0, 99999)
print(f'{i:05d}')

Search for f-strings here for more details.


... Python 2.6 and above:

print '{0:05d}'.format(i)

... before Python 2.6:

print "%05d" % i

See: https://docs.python.org/3/library/string.html

Solution 3 - Python

Python 3.6 f-strings allows us to add leading zeros easily:

number = 5
print(f' now we have leading zeros in {number:02d}')

Have a look at this good post about this feature.

Solution 4 - Python

You most likely just need to format your integer:

'%0*d' % (fill, your_int)

For example,

>>> '%0*d' % (3, 4)
'004'

Solution 5 - Python

Python 2.6 allows this:

add_nulls = lambda number, zero_count : "{0:0{1}d}".format(number, zero_count)

>>>add_nulls(2,3)
'002'

Solution 6 - Python

For Python 3 and beyond: str.zfill() is still the most readable option

But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?

    # if we want to pad 22 with zeros in front, to be 5 digits in length:
    str_output = '{:0>5}'.format(22)
    print(str_output)
    # >>> 00022
    # {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5

    # another example for comparision
    str_output = '{:#<4}'.format(11)
    print(str_output)
    # >>> 11##

    # to put it in a less hard-coded format:
    int_inputArg = 22
    int_desiredLength = 5
    str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength)
    print(str_output)
    # >>> 00022

Solution 7 - Python

You have at least two options:

  • str.zfill: lambda n, cnt=2: str(n).zfill(cnt)
  • % formatting: lambda n, cnt=2: "%0*d" % (cnt, n)

If on Python >2.5, see a third option in clorz's answer.

Solution 8 - Python

One-liner alternative to the built-in zfill.

This function takes x and converts it to a string, and adds zeros in the beginning only and only if the length is too short:

def zfill_alternative(x,len=4): return ( (('0'*len)+str(x))[-l:] if len(str(x))<len else str(x) )

To sum it up - build-in: zfill is good enough, but if someone is curious on how to implement this by hand, here is one more example.

Solution 9 - Python

A straightforward conversion would be (again with a function):

def add_nulls2(int, cnt):
	nulls = str(int)
	for i in range(cnt - len(str(int))):
		nulls = '0' + nulls
	return nulls

Solution 10 - Python

This is my Python function:

def add_nulls(num, cnt=2):
  cnt = cnt - len(str(num))
  nulls = '0' * cnt
  return '%s%s' % (nulls, num)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionramususView Question on Stackoverflow
Solution 1 - PythonunbeknownView Answer on Stackoverflow
Solution 2 - Pythonuser518450View Answer on Stackoverflow
Solution 3 - PythonSergioAraujoView Answer on Stackoverflow
Solution 4 - PythonSilentGhostView Answer on Stackoverflow
Solution 5 - PythonclorzView Answer on Stackoverflow
Solution 6 - PythonYunliuStorageView Answer on Stackoverflow
Solution 7 - PythontzotView Answer on Stackoverflow
Solution 8 - PythonGrzegorz WierzowieckiView Answer on Stackoverflow
Solution 9 - PythonrprView Answer on Stackoverflow
Solution 10 - PythonEmre KöseView Answer on Stackoverflow