Random String Generator

  • Share this:

Code introduction


This function generates a random string of a specified length from a set of characters, which can be specified. The default character set is all ASCII letters.


Technology Stack : math, os, random, string

Code Type : Generate random strings

Code Difficulty : Intermediate


                
                    
import math
import os
import random
import string

def generate_random_string(length, letters=string.ascii_letters):
    """Generate a random string of a given length from a set of letters.

    Args:
        length (int): The length of the random string to generate.
        letters (str, optional): The set of characters to choose from. Defaults to all ASCII letters.

    Returns:
        str: A random string of the specified length.
    """
    return ''.join(random.choice(letters) for i in range(length))