簡體   English   中英

如何在 python 中生成具有要求的隨機字符串?

[英]how can i generate random string with requirements in python?

我正在嘗試生成具有要求的隨機唯一代碼:

  1. 至少一個數字
  2. 至少一串
  3. 它應該是 8 個字符
  4. 一行中沒有重復的字符串和數字

這是我的代碼

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)

預期 Output:

1DXVQP7H
V3H6QP2K
R3562197
CDVQXHK9

上面代碼的問題是不符合第三點

random.choice(rndstr)保留為變量,並在選擇隨機數時將其從 8 減少

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

您可以使用randint選擇位數,無需列表可供選擇:

from string import ascii_uppercase as upp, digits as dig
from random import sample, shuffle, randint

for i in range(5):
    shuffle(s := sample(dig, n := randint(1, 7)) + sample(upp, 8-n))
    print("".join(s))

CYBOLN1K
3751NLIQ
05816R34
4012OC3E
GHWZB5SC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM