Thursday, 23 September 2021

Python: Generate random alpha numeric string

In this post, I am going to explain the program to generate random alpha numeric string using random module.

 

Step 1: Define a string that contains alphas numeric characters.

input = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

  Step 2: Select a random character from the input using random.randint method.

size_of_input = len(input)
random_index = random.randint(0, size_of_input-1)

 

Step 3: Iterate ‘n’ number of times and repeat the step 2 and attach the random selected character to the final result.

for i in range(length_of_str):
	random_index = random.randint(0, size_of_input-1)
	result += input[random_index]

 

Find the below working application.

 

random_alpha_numeric.py

 

import random

def generate_random_string(length_of_str):
    input = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    result = ''
    size_of_input = len(input)

    for i in range(length_of_str):
        random_index = random.randint(0, size_of_input-1)
        result += input[random_index]

    return result


print(generate_random_string(5))
print(generate_random_string(6))
print(generate_random_string(7))
print(generate_random_string(8))

 

Sample Output

sc3le
kKBGcv
uzS0s3m
O8ZiRmmy

 

 


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment