Random String Generator

  • Share this:

Code introduction


This function generates a random string of a specified length consisting of uppercase and lowercase letters and digits.


Technology Stack : Python built-in libraries: string, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import math
import os
import random
import re
import string

def generate_random_string(length):
    if not isinstance(length, int) or length <= 0:
        raise ValueError("Length must be a positive integer")
    
    characters = string.ascii_letters + string.digits
    random_string = ''.join(random.choice(characters) for i in range(length))
    return random_string