Random String Generator with Digit Option

  • Share this:

Code introduction


This function generates a random string of a specified length, with an option to include digits.


Technology Stack : random, string

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import string

def generate_random_string(length, use_digits=True):
    if length <= 0:
        return ""
    
    characters = string.ascii_letters
    if use_digits:
        characters += string.digits
    
    return ''.join(random.choice(characters) for _ in range(length))                
              
Tags: