Search code examples
pythonpython-3.xrandomgenerate

Python random string/text/code generator with fixed length and some characters


So, a few years ago I have found an exploit in the giftcard system at McDonalds. The basic point is by combining about 15-20 cards, and their codes, I got a point that 3rd and the 7th characters are the same while the others are completely random.

I might have found the same thing in the new Coke festival that is taken in my area (Turkey). I just wanted to ask, how can I develop a code with random module that it will randomly create codes by going over a specific algorithm, for example let's go with the same 3rd and 7th characters again.

By keeping them, randomly generate 8 numbered/lettered codes. Also I think using the while True would be better to generate like infinite amount of them. I will finally add them into a list. However, I need help in the middle part.

import random
import string

def randomStringDigits(stringLength=6):
    lettersAndDigits = string.ascii_letters + string.digits
    return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))

print ("Generating a Random String including letters and digits")
while True:
    print ("First Random String is  ", randomStringDigits(8))

Solution

  • You're almost there. I've just tweaked it a little - you could adjust it as is:

    import random
    
    numcount = 5
    fstring = ""
    length_of_code_you_want = 12
    position_to_keep_constant_1 = 2 # first position to keep constant is position 3, index 2
    position_to_keep_constant_2 = 6 # 2nd position to keep constant is position 7, index 6
    constant_1 = "J" # the value of the constant at position 3
    constant_2 = "L" # the value of the constant at position 7
    
    for num in range(length_of_code_you_want): #strings are 19 characters long
        if random.randint(0, 1) == 1:
            x = random.randint(1, 8)
            x += 96
            fstring += (chr(x).upper())
        elif not numcount == 0:
            x = random.randint(0, 9)
            fstring += str(x)
            numcount -= 1
    
    list_out = list(fstring)
    list_out[position_to_keep_constant_1] = str(constant_1)
    list_out[position_to_keep_constant_2] = str(constant_2)
    string_out = "".join(list_out)
    print(string_out)