简体   繁体   中英

Find number of digits in number

I need to generate a unique id for every user in my program. This is my code:

from random import choices
IDS = []
id = ""
num = int(input(" Entr the ids number : "))#عدد الايديات اللي بدك تسويها
len = int(input("Enter the length of the id:  "))#طول الايدي الواحد
def createId(num,len) :
        for i in range(num):
            id = ""
            for w in range(len):
                pl = str(choices([0,1,2,3,4,5,6,7,8,9])[0])
                id +=pl
                if id in IDS:
                    createId(1,len)
                else:
                    IDS.append(id)
                
def mll():
    len+=1
    createId(num,len)
    print(IDS)
    nn= 1
try:
    createId(num,len)
    print(IDS)
except :
    nn = 0
    while nn == 0 :
        try:
            mll()
        except:
            len +=1

But I have a problem. When I need to generate an id of 11 with length = 1, this is impossible. I need to increase the length to the minimum possible number of digits to accommodate the requested number.

How do I find how many digits a number has?

Try this:

from uuid import uuid4

def create_a_numeric_unique_id(width: int) -> str:
        return str(uuid4().int)[:width]

Output:

create_a_numeric_unique_id(8) => '26045809'

The easiest way to find how many digits a number has is:

len(str(num))

This converts the number to a string, then counts the number of characters in that string. (Note that you really do need to rename your len variable or else this won't work.)

If you'd like to do this working purely with numbers (which is more complicated but probably more efficient), see the answers to this question .

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