Random string generation with upper case letters and digits

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

    I was looking at the different answers and took time to read the documentation of secrets

    The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

    In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

    Looking more into what it has to offer I found a very handy function if you want to mimic an ID like Google Drive IDs:

    secrets.token_urlsafe([nbytes=None])
    Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is None or not supplied, a reasonable default is used.

    Use it the following way:

    import secrets
    import math
    
    def id_generator():
        id = secrets.token_urlsafe(math.floor(32 / 1.3))
        return id
    
    print(id_generator())
    

    Output a 32 characters length id:

    joXR8dYbBDAHpVs5ci6iD-oIgPhkeQFk
    

    I know this is slightly different from the OP's question but I expect that it would still be helpful to many who were looking for the same use-case that I was looking for.

提交回复
热议问题