如何转换十六进制字符串“\x89PNG”在Python中纯文本 [英] How to convert hex string "\x89PNG" to plain text in python
问题描述
我有一个字符串\x89PNG
,我想将它转换为纯文本。
I转介 http:// love- python.blogspot.in/2008/05/convert-hext-to-ascii-string-in-python.html
但是我发现它有点复杂。这可以用更简单的方式完成吗?
>>> s ='\x89PNG'
>>>打印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'
>>>打印s
\x70f = l\x26hl = en\x26geocode = \x26q\x3c
在这种情况下, string_escape
编码真的很有用:
>>> print s.decode('string_escape')
pf = 1& hl = en& geocode =& q<
关于编码的更多信息 - http://docs.python.org/library/codecs.html#standard-encodings
I have a string "\x89PNG"
which I want to convert to plain text.
I referred http://love-python.blogspot.in/2008/05/convert-hext-to-ascii-string-in-python.html But I found it a little complicated. Can this be done in a simpler way?
\x89PNG
is a plain text. Just try to print it:
>>> s = '\x89PNG'
>>> print s
┴PNG
The recipe in the link does nothing:
>>> hex_string = '\x70f=l\x26hl=en\x26geocode=\x26q\x3c'
>>> ascii_string = reformat_content(hex_string)
>>> hex_string == ascii_string
True
The real hex<->plaintext encoding\decoding is a piece of cake:
>>> s.encode('hex')
'89504e47'
>>> '89504e47'.decode('hex')
'\x89PNG'
However, you may have problems with strings like '\x70f=l\x26hl=en\x26geocode=\x26q\x3c'
, where '\'
and 'x'
are separate characters:
>>> s = '\\x70f=l\\x26hl=en\\x26geocode=\\x26q\\x3c'
>>> print s
\x70f=l\x26hl=en\x26geocode=\x26q\x3c
In this case string_escape
encoding is really helpful:
>>> print s.decode('string_escape')
pf=l&hl=en&geocode=&q<
More about encodings - http://docs.python.org/library/codecs.html#standard-encodings
这篇关于如何转换十六进制字符串“\x89PNG”在Python中纯文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!