Random String Generator

  • Share this:

Code introduction


This function generates a random string of a specified length, which can be used for password generation, captcha generation, and other scenarios.


Technology Stack : String manipulation, random number generation

Code Type : Generate random strings

Code Difficulty : Intermediate


                
                    
import datetime
import re
import random
import string
import math
import os
import sys
import subprocess

def generate_random_string(length=10):
    """Generate a random string of specified length.

    Args:
        length (int): Length of the random string to generate.

    Returns:
        str: Randomly generated string.
    """
    if not isinstance(length, int) or length < 0:
        raise ValueError("Length must be a non-negative integer.")
    
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))