jeudi 6 mai 2021

how can i generate random string with requirements in python?

I'm trying to generate random unique code with requirements :

  1. At least one number
  2. At least one string
  3. It should 8 characters
  4. No repeating strings and numbers in one line

here's my code

import random

chars = 'CDHKPQRVXY'
nums =  '123456789'
total = 10
rndstr = [1,2,3,4,5,6,7]
rndint = [1,2,3,4,5,6,7]
random.choice(rndstr)
random.choice(rndint)

for i in range(total):
    selects = random.sample(chars, random.choice(rndstr)) + random.sample(nums, random.choice(rndint))
    random.shuffle(selects)
    unique_code = ''.join(selects)
    print(unique_code)

Expected Output :

1DXVQP7H
V3H6QP2K
R3562197
CDVQXHK9

The problem with the code above is that it doesn't meet the third point




Aucun commentaire:

Enregistrer un commentaire