create a password with at least one number in python

Here is an example Python function to generate a password that includes at least one number:

main.py
import random
import re

def generate_password(length):
    """Generate a password of given length that includes at least one number"""
    password = ''
    while not re.search('\d', password):
        password = ''.join(random.choices(
            'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=length))
    return password
347 chars
11 lines

The function generates a random password of a given length, and then checks if it includes at least one digit using a regular expression. If not, it generates a new password and checks again. Once the password satisfies the condition, it is returned.

Example usage:

main.py
>>> generate_password(8)
'HRLgWEtr'
>>> generate_password(12)
'GWsJxchV7s1X'
77 chars
5 lines

gistlibby LogSnag