Random String Generator

  • Share this:

Code introduction


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


Technology Stack : Packages and technologies used in the code[English]

Code Type : Function

Code Difficulty : Intermediate


                
                    
import math
import os
import random
import re
import string

def generate_random_string(length, chars=string.ascii_letters + string.digits):
    """生成指定长度的随机字符串。

    Args:
        length (int): 字符串的长度。
        chars (str, optional): 用于生成字符串的字符集。默认为字母和数字。

    Returns:
        str: 生成的随机字符串。
    """
    return ''.join(random.choice(chars) for _ in range(length))