如何转换十六进制字符串“\x89PNG”在Python中纯文本 [英] How to convert hex string "\x89PNG" to plain text in python

查看:2187
本文介绍了如何转换十六进制字符串“\x89PNG”在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆