如何将带转义字符的bytes字符串转换为可正常解析转义的普通字符串
解决方法
问题核心:你的bytes序列中存储的\r、\n、\t是字面量字符组合,不是原生控制字符,直接按UTF-8解码只会保留字面转义符号,打印时不会触发转义效果。
最优解决方案
直接使用unicode_escape规则解码bytes即可:
bytes_string = b'Normal sentence\r\n\tIndented sentence\r\nanother one' # 用unicode_escape直接解码bytes string_that_I_want = bytes_string.decode('unicode_escape') print(string_that_I_want)
运行后输出效果和你预期完全一致:
Normal sentence Indented sentence another one
已完成UTF-8解码的场景处理
如果你已经把bytes转成了普通字符串,也可以通过二次编解码处理:
converted_string = str(bytes_string, 'utf-8') string_that_I_want = converted_string.encode('utf-8').decode('unicode_escape')
内容的提问来源于stack exchange,提问作者Omar Khalid
相关产品推荐
相关产品推荐

