Python 2.7 中字节字符串的处理求助

2015-01-27 10:33:23 +08:00
 ammzen

现在收到4个字节字符串 s,Python读取得到的是\xff\x08\x00\x0a
我想print显示为16进制, FF 08 00 0A

print '%X %X %X %X' %(s)
错误信息:TypeError: %X format: a number is required, not str

修改一下
print '%X %X %X %X' %(int(s))
错误信息:ValueError: invalid literal for int() with base 10: '\xff\x08'

后来又试了atoi
print '%X%X%X%X' %(string.atoi(s, 16))
错误信息:ValueError: invalid literal for int() with base 16: '\xff\x08\x00\n'

后来发现最大的问题在于 \x 转义,如果是0x的话倒是可以解决,想问一下有什么办法可以解决这个问题吗

4756 次点击
所在节点    Python
5 条回复
jatsz
2015-01-27 11:08:34 +08:00
s.encode('hex') #如果是想转成hex的字符串的话
print '%02X %02X %02X %02X' % (tuple(bytearray(s))) #带分隔的二进制字符串
wartime
2015-01-27 11:08:43 +08:00
print ' '.join('{:02X}'.format(ord(i)) for i in s)
ammzen
2015-01-27 11:11:21 +08:00
@wartime 我刚刚在stack上也找到这个^_^
ammzen
2015-01-27 11:12:26 +08:00
@jatsz 多谢!验证功能正常
Sylv
2015-01-27 11:24:09 +08:00
import binascii

s = '\xff\x08\x00\x0a'
s = [binascii.hexlify(c).upper() for c in s]
print ' '.join(s)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/165771

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX