【问题标题】:Python: How to convert bytestring to string?Python:如何将字节串转换为字符串?
【发布时间】:2021-01-11 06:51:11
【问题描述】:

功能:

    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 )

输出是这样的:

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

我想要的是写从这个字节值列表转换的字符串值

【问题讨论】:

  • 所以你想把它转换成普通文本?
  • 是的,正是鲁斯兰·托尔斯提考
  • 这能回答你的问题吗? Convert bytes to a string

标签: python-3.x string type-conversion


【解决方案1】:

你可以试试这个:

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

而不是这个:

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

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 2017-01-19
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    相关资源
    最近更新 更多