2012-07-27 59 views
1

我有一个字符串"\x89PNG",我想将它转换为纯文本。如何将十六进制字符串“ x89PNG”转换为python中的纯文本

我提到http://love-python.blogspot.in/2008/05/convert-hext-to-ascii-string-in-python.html 但我发现它有点复杂。这可以用更简单的方式完成吗?

+2

什么是你希望它是什么? – 2012-07-27 06:11:45

+0

我没有看到任何复杂的方式。只需参阅片段中使用的模块文档即可。 http://docs.python.org/library/binascii.html http://docs.python.org/library/re.html#module-re – Babu 2012-07-27 06:12:52

+0

你是否真的期待它是1000字? – 2012-07-27 06:21:25

回答

4

\x89PNG的纯文本。只是尝试打印:

>>> s = '\x89PNG' 
>>> print s 
┴PNG 

中的链接配方无助:

>>> hex_string = '\x70f=l\x26hl=en\x26geocode=\x26q\x3c' 
>>> ascii_string = reformat_content(hex_string) 
>>> hex_string == ascii_string 
True 

真正的十六进制< - >明文编码\解码是小菜一碟:

>>> s.encode('hex') 
'89504e47' 
>>> '89504e47'.decode('hex') 
'\x89PNG' 

但是,您可能会遇到像'\x70f=l\x26hl=en\x26geocode=\x26q\x3c'这样的字符串问题,其中'\''x'是分开的字符:

>>> s = '\\x70f=l\\x26hl=en\\x26geocode=\\x26q\\x3c' 
>>> print s 
\x70f=l\x26hl=en\x26geocode=\x26q\x3c 

在这种情况下string_escape编码是真正有用的:

>>> print s.decode('string_escape') 
pf=l&hl=en&geocode=&q< 

更多编码 - http://docs.python.org/library/codecs.html#standard-encodings

相关问题