Random String Generator

  • Share this:

Code introduction


This function generates a random string of a specified length, composed of letters and digits.


Technology Stack : string, random

Code Type : Generate random strings

Code Difficulty : Intermediate


                
                    
import random
import string

def generate_random_string(length):
    if not isinstance(length, int) or length < 1:
        raise ValueError("Length must be a positive integer")

    characters = string.ascii_letters + string.digits
    return ''.join(random.choice(characters) for i in range(length))                
              
Tags: