简体   繁体   English

需要有关随机字符串生成的帮助 python

[英]Need help regarding random string generation python

What I want is to generate a string in this specific format: l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l With each l and d being a different string or number.我想要的是以这种特定格式生成一个字符串:l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d +l+l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l 每个 l 和 d 是不同的字符串或数字。 The issue is when I try to generate, the whole thing is the same value/string.问题是当我尝试生成时,整个东西都是相同的值/字符串。 But I want it different.但我想要它不同。 Here is an example: What I am getting: lll9999l9llll9999l9llll9999l9llll9999l9l What I need: bfb7491w3anfr4530x2zzbg9891u2rbep8421m9s这是一个例子:

def id_gen():
    l = random.choice(string.ascii_lowercase)
    d = random.choice(string.digits)
    id = l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l+l+l+l+d+d+d+d+l+d+l
    print(id)

The result:结果:

lll9999l9llll9999l9llll9999l9llll9999l9l

I need this to generate something different:)我需要这个来产生不同的东西:)

This seems to work for me:这似乎对我有用:

def gen_id() :
    pattern = 'lllddddldllllddddldllllddddldllllddddldl'
    digits = [random.choice(string.digits) for i in range(len(pattern))]
    letters = [random.choice(string.ascii_lowercase) for i in range(len(pattern))]
    return ''.join( digits[i] if pattern[i] == 'd' else letters[i] for i in range(len(pattern)) )

testing:测试:

>>> gen_id()
'lnx1066k0hnrd5409d1nhgo1254t6rzyw5165f8v'
>>> gen_id()
'sbc7119f4ythd8845i1afay1900f4wjcv0659b4e'
>>> gen_id()
'yan6228r0nebj5097y7jnwh7065s7osra0391j5f'
>>> 

seems different enough... please, don't forget to import string, random =)似乎足够不同......拜托,不要忘记import string, random =)

To not consume the random generator, IMHO this is the best solution:为了不消耗随机生成器,恕我直言,这是最好的解决方案:

def gen_id(pattern) :
    l = len(pattern)
    d = pattern.count('d')
    digits = random.choices(string.digits, d)
    letters = random.choices(string.ascii_lowercase, l-d)
    return ''.join( digits.pop() if pattern[i] == 'd' else letters.pop() for i in range(l) )

You can use this to get a random combination of letters and digits in the desired order:您可以使用它来按所需顺序随机组合字母和数字:

def letter():
    return random.choice(string.ascii_lowercase)

def digit():
    return random.choice(string.digits)

def id_gen():
    return letter() + digit() + letter() + letter()  # ldll

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM