Random string generation with upper case letters and digits

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

    From Python 3.6 on you should use the secrets module if you need it to be cryptographically secure instead of the random module (otherwise this answer is identical to the one of @Ignacio Vazquez-Abrams):

    from secrets import choice
    import string
    
    ''.join([choice(string.ascii_uppercase + string.digits) for _ in range(N)])
    

    One additional note: a list-comprehension is faster in the case of str.join than using a generator expression!

提交回复
热议问题