Random strings in Python 2.6 (Is this OK?)

前端 未结 5 1655
独厮守ぢ
独厮守ぢ 2020-12-12 12:54

I\'ve been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to

\'\'.join(r         


        
相关标签:
5条回答
  • 2020-12-12 13:22

    Regarding the last example, the following fix to make sure the line is even length, whatever the junk_len value:

    junk_len = 1024
    junk =  (("%%0%dX" % (junk_len * 2)) % random.getrandbits(junk_len * 8)).decode("hex")
    
    0 讨论(0)
  • 2020-12-12 13:24

    It seems the fromhex() method expects an even number of hex digits. Your string is 75 characters long. Be aware that something[:-1] excludes the last element! Just use something[:].

    0 讨论(0)
  • 2020-12-12 13:35

    Taken from the 1023290 bug report at Python.org:

    junk_len = 1024
    junk =  (("%%0%dX" % junk_len) % random.getrandbits(junk_len *
    8)).decode("hex")
    

    Also, see the issues 923643 and 1023290

    0 讨论(0)
  • 2020-12-12 13:40

    Sometimes a uuid is short enough and if you don't like the dashes you can always.replace('-', '') them

    from uuid import uuid4
    
    random_string = str(uuid4())
    

    If you want it a specific length without dashes

    random_string_length = 16
    str(uuid4()).replace('-', '')[:random_string_length]
    
    0 讨论(0)
  • 2020-12-12 13:46
    import os
    random_string = os.urandom(string_length)
    

    and if you need url safe string :

    import os
    random_string = os.urandom(string_length).hex() 
    

    (note random_string length is greatest than string_length in that case)

    0 讨论(0)
提交回复
热议问题