如何解码字节对象的字符串表示形式? [英] How to decode a string representation of a bytes object?

查看:89
本文介绍了如何解码字节对象的字符串表示形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,其中包含编码的字节:

I have a string which includes encoded bytes inside it:

str1 = "b'Output file \xeb\xac\xb8\xed\x95\xad\xeb\xb6\x84\xec\x84\x9d.xlsx Created'"

我想对其进行解码,但是由于它已经变成字符串,所以我不能。因此,我想问是否有任何方法可以将其转换为

I want to decode it, but I can't since it has become a string. Therefore I want to ask whether there is any way I can convert it into

str2 = b'Output file \xeb\xac\xb8\xed\x95\xad\xeb\xb6\x84\xec\x84\x9d.xlsx Created'

这里 str2 是一个 bytes 对象,我可以对其进行解码

Here str2 is a bytes object which I can decode easily using

str2.decode('utf-8')

以获得最终结果:

'Output file 문항분석.xlsx Created'


推荐答案

一种简单的方法是假定初始字符串的所有字符都在[0,256)范围内,并映射到相同的Unicode值,这意味着它是Latin1编码的字符串。

A simple way is to assume that all the characters of the initial strings are in the [0,256) range and map to the same Unicode value, which means that it is a Latin1 encoded string.

然后琐碎:

str1[2:-1].encode('Latin1').decode('utf8')

这篇关于如何解码字节对象的字符串表示形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆