Random String Generator

  • Share this:

Code introduction


This function is used to generate a random string of a specified length, which is often used in scenarios such as password generation and captcha generation.


Technology Stack : datetime, random, string, json

Code Type : Generate random strings

Code Difficulty : Beginner


                
                    
import datetime
import random
import string
import json

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