Random String Generator

  • Share this:

Code introduction


This function generates a random string of a specified length, containing both uppercase and lowercase letters and digits.


Technology Stack : string, random

Code Type : Generate random strings

Code Difficulty : Intermediate


                
                    
import math
import random
import string

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