Random string generation with upper case letters and digits

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

    This method is slightly faster, and slightly more annoying, than the random.choice() method Ignacio posted.

    It takes advantage of the nature of pseudo-random algorithms, and banks on bitwise and and shift being faster than generating a new random number for each character.

    # must be length 32 -- 5 bits -- the question didn't specify using the full set
    # of uppercase letters ;)
    _ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
    
    def generate_with_randbits(size=32):
        def chop(x):
            while x:
                yield x & 31
                x = x >> 5
        return  ''.join(_ALPHABET[x] for x in chop(random.getrandbits(size * 5))).ljust(size, 'A')
    

    ...create a generator that takes out 5 bit numbers at a time 0..31 until none left

    ...join() the results of the generator on a random number with the right bits

    With Timeit, for 32-character strings, the timing was:

    [('generate_with_random_choice', 28.92901611328125),
     ('generate_with_randbits', 20.0293550491333)]
    

    ...but for 64 character strings, randbits loses out ;)

    I would probably never use this approach in production code unless I really disliked my co-workers.

    edit: updated to suit the question (uppercase and digits only), and use bitwise operators & and >> instead of % and //

提交回复
热议问题