7

For example, in your python shell(IDLE):

>>> a = "\x3cdiv\x3e"
>>> print a

The result you get is:

<div>

but if a is an ascii encoded string:

>>> a = "\\x3cdiv\\x3e" ## it's the actual \x3cdiv\x3e string if you read it from a file
>>> print a

The result you get is:

\x3cdiv\x3e

Now what i really want from a is <div>, so I did this:

>>> b = a.decode("ascii")
>>> print b

BUT surprisingly I did NOT get the result I want, it's still:

\x3cdiv\x3e

So basically what do I do to convert a, which is \x3cdiv\x3e to b, which should be <div>?

Thanks

4

2 回答 2

14
>>> a = rb"\x3cdiv\x3e"
>>> a.decode('unicode_escape')
'<div>'

还可以查看一些有趣的编解码器

于 2013-05-11T03:02:29.667 回答
5

使用python 3.x,您可以调整 Kabie 的答案

a = b"\x3cdiv\x3e"
a.decode('unicode_escape')

或者

a = b"\x3cdiv\x3e"
a.decode('ascii')

都给

>>> a
b'<div>'

什么是b前缀?

字节文字总是以'b'或'B'为前缀;它们生成 bytes 类型而不是 str 类型的实例。它们可能只包含 ASCII 字符;数值为 128 或更大的字节必须用转义表示。

于 2013-05-11T08:57:45.587 回答