简体   繁体   English

Python:如何将字节串转换为字符串?

[英]Python: How to convert bytestring to string?

the function: function:

    f = open('image.txt', 'wb')
    byte_arr = getbytes(read_bits())
    byte_list = list(byte_arr)
    print(byte_list)
    some_bytes = bytearray(byte_list)
    print(bytes(some_bytes))
    st = bytes(some_bytes).decode('latin1')
    immutable_bytes = bytes(some_bytes)
    with open('test','wb') as f:
         f.write(immutable_bytes )

the output is like: output 就像:

b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00'

what I want is to write string value converted from this list of byte values我想要的是写从这个字节值列表转换的字符串值

You could try this:你可以试试这个:

st = bytes(some_bytes).decode('utf-8')
with open('test','wb') as f:
     f.write(st)

instead of this:而不是这个:

st = bytes(some_bytes).decode('latin1')
immutable_bytes = bytes(some_bytes)
with open('test','wb') as f:
     f.write(immutable_bytes )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM