yes, to make life easy lets use an easy example.
#lets import random, to generate random stuff
import random
#create a result string
result = ''
nums = [1,2,3,4,5,6,7,8,9,0]
for i in range(6):
result += str(random.choice(nums))
print(result)
Answer from NemoMeMeliorEst on Stack OverflowI am new to programming, I am currently trying to create an App Game, i want to be able to assign every user a unique 4 digit number. Right now i have this
numid = random.randint(1111,9999)
this will assign an ID to user A.... Is there a way to ensure that when i create user B their unique ID cannot be a repeat?
How to generate a 4 digit random number which contains unique digits in python3?
pandas - Generating all 4 digit unique code in Python - Stack Overflow
Generate a unique number for each entry
python 3.x - Four strings generate unique ids - Stack Overflow
yes, to make life easy lets use an easy example.
#lets import random, to generate random stuff
import random
#create a result string
result = ''
nums = [1,2,3,4,5,6,7,8,9,0]
for i in range(6):
result += str(random.choice(nums))
print(result)
UUID is for generating Universally Unique Identifiers, which have a particular structure and won't be what you're after.
You can use the random module as follows
import random
id = ''.join(str(random.randint(0,10)) for x in range(6))
print(id)
What does this do?
randintgenerates a random number between 0 inclusive and 10 exclusive, i.e. 0-9- calling this with
for x in range(6)generates six random digits strconverts the digits to strings''.joinforms a single string from the digits
Well you could use uuid.hex
import uuid
uuid.uuid4().hex[:8] # Might reduce uniqueness because of slicing
Or Django also has helper function get_random_string which accepts two parameters length (default=12) and allowed_chars:
from django.utils.crypto import get_random_string
get_random_string(8)
Use os.urandom for the data, and base64 encode it;
In [1]: import os
In [2]: import base64
In [3]: base64.b64encode(os.urandom(6)).decode('ascii')
Out[3]: '6Amtry80'
You could just hash your id :
import hashlib
id = 12
hashlib.sha256(str(id).encode()).hexdigest() # with python2.x you don't need to encode()
# => '6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918'
You'll have to store the correspondance somewhere though, because there is no way to retrieve the id from a hash.
from python uuid doc, uuid1 is dependent on current time.
You could use uuid3 to have a reproducible uuid for the same input, by reusing the same namespace:
namespace = uuid.uuid4()
...
print uuid.uuid3(namespace, "1")