[英]How do you decode an ascii string in python?
For example, in your python shell(IDLE): 例如,在您的python shell(IDLE)中:
>>> a = "\x3cdiv\x3e"
>>> print a
The result you get is: 您得到的结果是:
<div>
but if a
is 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 a
is <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\\x3e
to b
, which should be <div>
? 因此,基本上我该怎么做将
a
( \\x3cdiv\\x3e
为b
(应为<div>
?
Thanks 谢谢
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 b
prefix for ? b
前缀是什么?
Bytes literals are always prefixed with 'b' or 'B';
字节字面量始终以“ b”或“ B”为前缀; they produce an instance of the bytes type instead of the str type.
它们产生字节类型而不是str类型的实例。 They may only contain ASCII characters;
它们只能包含ASCII字符; bytes with a numeric value of 128 or greater must be expressed with escapes.
数值等于或大于128的字节必须用转义符表示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.