[英]Python 2.7: how to prevent automatic decoding from hex to string
I'm working with the python socket module, playing around with a udp client I wrote. 我正在使用python套接字模块,与我编写的udp客户端一起玩。 I dislike how its handling my hex literals.
我不喜欢它如何处理我的十六进制文字。 example:
例:
>>> querydns = '\xb9\x1b\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03\x77\x77\x77\x06\x67\x6f\x6f\x67\x6c\x65\x03\x63\x6f\x6d\x00\x00\x01\x00\x01'
>>> querydns
'\xb9\x1b\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01'
>>> replydata
'\xb9\x1b\x81\x80\x00\x01\x00\x06\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0j\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0i\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0\x93\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0g\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0h\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0c'
Notice how it automatically decodes some of the hex into characters? 请注意,它是如何自动将某些十六进制解码为字符的? I want to deal with only hex values, no @'s or www's.
我只想处理十六进制值,不能处理@或www。 Is there an easy way to stop this automatic decoding?
有没有简单的方法可以停止这种自动解码?
you cant really ... you have a few options(sort of) 你真的不能...你有几个选择
import binascii
print binascii.hexlify(querydns)
or fake it(it takes more effort to preserve leading zeros)... 或伪造它(保留前导零需要更多的努力)...
print "".join("\\x%s"%(hex(ord(data_byte))[2:]) for data_byte in querydns)
or a combination I guess would work 或者我认为可以组合使用
hexy = binascii.hexlify(querydns)
print "".join("\\x%s"%hexy[i:i+2] for i in range(len(hexy)-1))
You can use it as 'raw' string by putting a 'r' before the string. 您可以在字符串前面加上“ r”,将其用作“原始”字符串。 A raw string is not processed by the python and is taken as it is.
原始字符串不会由python处理,而是按原样使用。
string = r"example string"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.