How can I convert a python urandom to a string?

前端 未结 4 614
无人共我
无人共我 2020-12-13 02:48

If I call os.urandom(64), I am given 64 random bytes. With reference to Convert bytes to a Python string I tried

a = os.urandom(64)
a.decode()
a.decode(\"utf         


        
相关标签:
4条回答
  • 2020-12-13 03:04

    The code below will work on both Python 2.7 and 3:

    from base64 import b64encode
    from os import urandom
    
    random_bytes = urandom(64)
    token = b64encode(random_bytes).decode('utf-8')
    
    0 讨论(0)
  • 2020-12-13 03:06

    You can use base-64 encoding. In this case:

    a = os.urandom(64)
    a.encode('base-64')
    

    Also note that I'm using encode here rather than decode, as decode is trying to take it from whatever format you specify into unicode. So in your example, you're treating the random bytes as if they form a valid utf-8 string, which is rarely going to be the case with random bytes.

    0 讨论(0)
  • 2020-12-13 03:24

    You have random bytes; I'd be very surprised if that ever was decodable to a string.

    If you have to have a unicode string, decode from Latin-1:

    a.decode('latin1')
    

    because it maps bytes one-on-one to corresponding Unicode code points.

    0 讨论(0)
  • 2020-12-13 03:24

    this easy way:

    a = str(os.urandom(64))
    print(F"the: {a}")
    print(type(a))
    
    0 讨论(0)
提交回复
热议问题