Search code examples
pythonrandomkeygenerate

Generating Numbers/Text in certain way/form


Working on a script to generate a Key of letters/numbers in a certain way, I need to generate the key in a format like shown here xxxx-xxxx-xxxx, i would generate the key in replace of the xxxx-xxxx-xxxx like 19n3-m1m9-1nl1 but then generate this key in front of another string like Key=xxxx-xxxx-xxxx so Key=19n3-m1m9-1nl1 and loop it multiple times then save this string in a text file


Solution

  • If you provide more detail I'll be able to answer your question better, but here is how I would achieve what I think it is you're attempting:

    1: Import relevant modules

    import random, string
    

    2: Generate random string of 16 letters / digits. Note this will not evenly distribute numbers/letters throughout the key like the example you gave - please let me know if this is a requirement.

    key = ''.join(random.choices(string.ascii_lowercase + string.digits, k=16))
    

    3: "Join" groups of 4 characters with a dash.

    key = '-'.join([key[:4], key[4:8], key[8:12], key[12:16]])
    

    4: Lastly, add "Key=" to the start of the string:

    key = "Key=" + key
    

    5: Example output:

    'Key=ed2o-kn7o-jyif-18wo'
    

    You can save this to a text file using:

    text_file = open("keys.txt", "w")
    text_file.write(key)
    text_file.close()