简体   繁体   中英

How to print an ID number include leading zeros?

I'm writing an Iterator class that generate all possible ID numbers. the issue is that I need it to print all 9 digit numbers including the ones that starts with 0 for example: 000000001 000000002 ect.

I need the output as a number and not a string, is there a way to do it?

my code:

class IDIterator:
    def __init__(self):
        self._id = range(000000000, 1000000000)
        self._next_id = 000000000

    def __iter__(self):
        return self

    def __next__(self):
        self._next_id += 1
        if self._next_id == 999999999:
            raise StopIteration

        return self._next_id

ID = iter(IDIterator())
print(next(ID))
print(next(ID))
print(next(ID))

output = 1 2 3 ..

Python has a built in string function which will perform the left-padding of zeros

>>> before = 1
>>> after = str(before).zfill(9)
000000001
>>> type(after)
<class 'str'>

If you need the ID returned as an integer number with leading zeros preserved, I don't believe there's a way to do what you're looking for--the primitive Python type simply does not support this type of representation. Another strategy would be to store the ID's as normal integers and format with leading zeros when you need to display something to the user.

def format_id(string, length=9):
    return str(string).zfill(length)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM