Reputation: 100
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. 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 :)
Upvotes: 2
Views: 106
Reputation: 3460
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) )
Upvotes: 0
Reputation: 23528
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
=)
Upvotes: 4
Reputation: 26039
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
Upvotes: -1