create a password with a custom length and lowercase letters in python

main.py
import random
import string

def generate_password(length):
    """Generate a random password with lowercase letters of given length"""
    lowercase_letters = string.ascii_lowercase
    password = ''.join(random.choice(lowercase_letters) for i in range(length))
    return password
283 chars
9 lines

Explanation:

  • string.ascii_lowercase returns all the letters of the lowercase alphabet.
  • random.choice returns a random element from the given iterable, in this case:lowercase_letters.
  • join() method is used to create a single string from a list of strings (in this case, the list of random letters).

Usage:

main.py
password_length = 8
password = generate_password(password_length)
print(password)    # Example output: "xjhtvlfw"
114 chars
4 lines

gistlibby LogSnag