Random Word Generator: Case-Specific Options

  • Share this:

Code introduction


The function generates a random word of a specified length, and can generate words in uppercase, lowercase, or mixed case according to the need.


Technology Stack : The function uses the 'random' and 'string' modules to generate random words of a specified length, and can generate words in uppercase, lowercase, or mixed case.

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_word_generator(word_length, case='lower'):
    """
    Generate a random word with the specified length.

    Parameters:
    - word_length (int): The length of the word to generate.
    - case (str): The case of the generated word ('lower', 'upper', 'random').

    Returns:
    - str: A random word of the specified length and case.
    """
    import random
    import string

    if case == 'lower':
        return ''.join(random.choices(string.ascii_lowercase, k=word_length))
    elif case == 'upper':
        return ''.join(random.choices(string.ascii_uppercase, k=word_length))
    elif case == 'random':
        return ''.join(random.choices(string.ascii_letters, k=word_length))
    else:
        raise ValueError("Invalid case option. Choose 'lower', 'upper', or 'random'.")