Random string generation with upper case letters and digits

前端 未结 30 3171
逝去的感伤
逝去的感伤 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:12

    If you need a random string rather than a pseudo random one, you should use os.urandom as the source

    from os import urandom
    from itertools import islice, imap, repeat
    import string
    
    def rand_string(length=5):
        chars = set(string.ascii_uppercase + string.digits)
        char_gen = (c for c in imap(urandom, repeat(1)) if c in chars)
        return ''.join(islice(char_gen, None, length))
    

提交回复
热议问题