[英]How to decode non-b-prefixed string like '\xd0\xbc' stored in variable in python3?
I have some variable from API. 我有一些来自API的变量。 For example:
例如:
a == '\xd0\xbc'
I need to get variable b by decoding a: 我需要通过解码a获得变量b:
b == 'М'
But I can't write in code something like this: 但是我不能用这样的代码写:
a = b'\xd0\xbc'
b = a.decode()
because this text (\\xd0\\xbc) is already in the variable. 因为此文本(\\ xd0 \\ xbc)已在变量中。
will this help ? 这会有所帮助吗? I would guess there is a better way however I do not know it
我猜有更好的方法,但是我不知道
>>> a = r'\xd0\xbc'
>>> b = 'b"{}"'.format(a)
>>> c = eval(b)
>>> d = c.decode()
>>> d
'\u043c'
You need to use str.encode()
and pass encoding="latin"
to get b == 'M'
. 您需要使用
str.encode()
并传递encoding="latin"
来获得b == 'M'
。
a = str.encode('\xd0\xbc', 'latin')
b = a.decode()
print(b)
If "latin"
is not the standard encodings you were looking for, try others . 如果
"latin"
不是您想要的标准编码,请尝试其他 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.