Python Program to Generate a Random alphanumeric String

282
views
Random alphanumeric String
(Last Updated On: September 23, 2018)

In this program, you’ll learn how to how to generate a random alphanumeric String in Python.

To properly understand this Generation of the Random alphanumeric string program, you should have the knowledge of following Python programming topics:

  1. Python Input, Output and Import
  2. Python random module

To generate any random alphanumeric, UUID function is used in Python. This function is defined in the random module and UUID.

Program to Generate a Random Alphanumeric String

import uuid

def my_random_string(string_length=10):
    """Returns a random string of length string_length."""

# Convert UUID format to a Python string.
    random = str(uuid.uuid4())

# Make all characters uppercase.
    random = random.upper()

# Remove the UUID '-'.
    random = random.replace("-","")

# Return the random string.
    return random[0:string_length]

print(my_random_string(6)) # For example, D9E50C

Output:

38B453

Note: we can get a different number and alphabet as this Program generates any random number and alphabet. and numbers will range from 0 – 9 and alphabet will range from A – B, as all alphabet will be capital because we have specified that. The syntax of this random function is:

print(my_random_string(n))

If you want you can change ‘n’ and get desired no output i.e if you put n=9 the output will be 9 characters.

n=1

12BA5FA1B

Related Programs:

Ask your questions and clarify your/others doubts on how to generate a random alphanumeric String in Python by commenting. Python Documentation