Generating random identifiers in Python

Python Methods and Functions

There are different ways to create identifiers in python. Let's see how different types of identifiers can be generated using Python without using the built-in Python libraries.

1. Generating a random integer as identifiers

Code # 1: print 10 random values ​​of numbers from 1 to 100.

# Python3 demo code
# randomly generate integer IDs

 

import random

 
# defines how many values ​​
# will be printed

for x in range ( 10 ):

 

  # output 10 random values ​​

# from 1 to 100

print (random.randint ( 1 , 101 ))

Output:

 76 72 7 78 77 19 24 23 77 96 

Code # 2: print random numbers from 1 to 100, multiples of 5.

# Python3 demo code
# randomly generated identifiers
# which consist of 5

  

import random

 
# defines how many
# values ​​will be printed

for x in range ( 10 ):

 

# output 10 random values ​​between

# 1 and 100 multiples of 5

print (random .randint ( 1 , 20 ) * 5 )

Output:

 60 30 35 100 85 25 100 20 90 85 

Drawbacks:

  • Generating Random numbers is not unique, Same number can repeat itself.
  • It generates only Integer values.
  • 2. Generating random string as identifiers

    Generating random string identifiers consists of letters and numbers. This can be useful when generating passwords as they provide encryption and decryption techniques.

    Code # 1: Show how to generate random string IDs.

    # Python3 demo code
    # randomly generate line IDs

     

    import random

    import string

     
    # Generate a random line
    # with 32 characters.

    random = ' '.join ([random.choice (string.ascii_letters

    + string.digits) for n in range ( 32 )])

     
    # print random
    # 32 string

    print (random)

    Output:

     Rf2IdqUNkURNN6mw82kSpyxQe9ib3usX 

    Code # 2: Using a function call

    # Python3 code for demonstration
    # randomly generating line IDs

     

    import random

    import string

     
    # function definition for random
    # line identifier with the parameter

    def ran_gen (size, chars = string.ascii_uppercase + string.digits):

      return ' '.join (random.choice (chars) for x in range (size))

      
    # function call for a random string
    # generation with size 8 and line

    print (ran_gen ( 8 , "AEIOSUMA23" ))

    Output:

     S2M2IEAO 



    Tutorials