In this article, we will see how to implement a function that will generate a random hash of the specified format with the given length.

The below function generates the random hash of the following formats.

  • Alpha numeric
  • Apha lower with special characters included (_-).
  • Alpha
  • Alpha numeric lower
  • Hexadecimal
  • Numeric
  • Numeric with non zero
import random
import string

def random_hash(format: str, length: int) -> str:
    pool = ""

    if format == "alnum":
        pool = string.digits + string.ascii_letters
    elif format == "alpSpecLower":
        pool = string.ascii_lowercase + "-_"
    elif format == "alpha":
        pool = string.ascii_letters
    elif format == "alpNumLower":
        pool = string.digits + string.ascii_lowercase
    elif format == "hexdec":
        pool = string.hexdigits[:-6]
    elif format == "numeric":
        pool = string.digits
    elif format == "nozero":
        pool = "123456789"
        return ""

    # allocate a new list to store the hash
    buf = [random.choice(pool) for _ in range(length)]

    return "".join(buf)
print("alnum : " + random_hash("alnum", 10))
print("alpSpecLower : " + random_hash("alpSpecLower", 10))
print("alpha : " + random_hash("alpha", 10))
print("alpNumLower : " + random_hash("alpNumLower", 10))
print("hexdec : " + random_hash("hexdec", 10))
print("numeric : " + random_hash("numeric", 10))
print("nozero : " + random_hash("nozero", 10))


  • The above function takes two arguments: format and length, where format is a string that specifies the type of characters to use in the hash, and length is an integer that specifies the length of the hash.
  • The first thing the function does is define an empty string pool. This string will be populated with the characters that are allowed for the given format.
  • The function then uses an if-elif-else statement to populate pool based on the value of format. If format is not one of the specified formats, the function returns an empty string.
  • Next, the function initializes a list buf of length length. This list will store the characters of the generated hash.
  • The buf list is filled with random characters from pool using a list comprehension. Each character is chosen randomly using the random.choice function.
  • Finally, the buf list is shuffled using the random.shuffle function, and the shuffled list is converted to a string using the join method and the resultant string is returned as the output of the function.

Categorized in:

Tagged in: