You can download this code by clicking the button below.
This code is now available for download.
Generates a random string of a specified length, used in cryptography, data encryption, or other scenarios requiring random strings.
Technology Stack : Python built-in libraries: string, random
Code Type : Function
Code Difficulty : Intermediate
import math
import os
import random
import re
import string
def random_string(length=10):
"""Generate a random string of specified length.
Args:
length (int): The length of the random string to generate.
Returns:
str: A random string of the specified length.
"""
if not isinstance(length, int) or length < 1:
raise ValueError("Length must be a positive integer.")
letters = string.ascii_letters
result_str = ''.join(random.choice(letters) for i in range(length))
return result_str