-1

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 ..

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
T.Stimer
  • 255
  • 1
  • 2
  • 8
  • Does this answer your question? [Display number with leading zeros](https://stackoverflow.com/questions/134934/display-number-with-leading-zeros) – Pranav Hosangadi Oct 15 '20 at 01:00

1 Answers1

0

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)
vulpxn
  • 731
  • 1
  • 6
  • 14