Random string generation with upper case letters and digits

前端 未结 30 3218
逝去的感伤
逝去的感伤 2020-11-22 02:51

I want to generate a string of size N.

It should be made up of numbers and uppercase English letters such as:

  • 6U1S75
  • 4Z4UKK
  • U911K4
30条回答
  •  灰色年华
    2020-11-22 03:11

    (1) This will give you all caps and numbers:

    import string, random
    passkey=''
    for x in range(8):
        if random.choice([1,2]) == 1:
            passkey += passkey.join(random.choice(string.ascii_uppercase))
        else:
            passkey += passkey.join(random.choice(string.digits))
    print passkey 
    

    (2) If you later want to include lowercase letters in your key, then this will also work:

    import string, random
    passkey=''
    for x in range(8):
        if random.choice([1,2]) == 1:
            passkey += passkey.join(random.choice(string.ascii_letters))
        else:
            passkey += passkey.join(random.choice(string.digits))
    print passkey  
    

提交回复
热议问题