Random string generation with upper case letters and digits

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

    I'd do it this way:

    import random
    from string import digits, ascii_uppercase
    
    legals = digits + ascii_uppercase
    
    def rand_string(length, char_set=legals):
    
        output = ''
        for _ in range(length): output += random.choice(char_set)
        return output
    

    Or just:

    def rand_string(length, char_set=legals):
    
        return ''.join( random.choice(char_set) for _ in range(length) )
    

提交回复
热议问题