你如何在python中解码一个ascii字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16493211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:48:56  来源:igfitidea点击:

How do you decode an ascii string in python?

pythonstringcharacter-encodingascii

提问by Shane

For example, in your python shell(IDLE):

例如,在你的 python shell(IDLE) 中:

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

The result you get is:

你得到的结果是:

<div>

but if ais an ascii encoded string:

但如果a是一个ASCII编码的字符串:

>>> 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 ais <div>, so I did this:

现在我真正想要的a<div>,所以我这样做了:

>>> 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\x3eto b, which should be <div>?

所以基本上我该怎么办转换a,这是\x3cdiv\x3eb,这应该是<div>

Thanks

谢谢

采纳答案by Kabie

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

Also check out some interesting codecs.

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

回答by kiriloff

With python 3.x, you would adapt Kabie answer to

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

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

or

或者

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

both give

都给

>>> a
b'<div>'

What is bprefix for ?

什么是b前缀?

Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

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