Python字节字符串在字典中打印不正确 [英] Python byte string print incorrectly in dictionary

查看:165
本文介绍了Python字节字符串在字典中打印不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑一个列表,其中包含以字节为单位的数据(即['\x03','\x00','\x32',...])

Consider a list contains data in byte (i.e ['\x03', '\x00', '\x32', ... ])

temp = b''

for c in field_data:
   temp += c
   print "%x" % ord(c)

正确地将所有字节连接为temp(字节字面量)。但是,当我将其添加到字典元素中时,在某些情况下输出是错误的。

above code correctly concatenates all bytes into temp (byte string literal). But when I added this into element of dictionary, output was incorrect in some cases.

testdic = {'dd':temp}
print testdic

例如,列表中有0x0 0x0 0x0 0x0 0x0 0x0 0x33 0x32第一个代码显示所有字节均已正确连接。但是当我紧接着执行第二个代码时,输​​出是这样的:

For example, 0x0 0x0 0x0 0x0 0x0 0x0 0x33 0x32 are in list and first code show all bytes were correctly concatenated. But when I executed second code right after, output was like this:

{'dd': '\x00\x00\x00\x00\x00\x0032'}

我不确定为什么会这样。

And I'm not entirely sure why this happens.

推荐答案

当打印 dict 时,它会打印括号 {} 以及内容的表示形式

When you print a dict, it prints the braces { and } along with a representation of the contents.

>>> b = b'\x00\x0f\xff'
>>> print b
�
>>> print repr(b)
'\x00\x0f\xff'
>>> print {'test':b}
{'test': '\x00\x0f\xff'}

编辑

数字0x33& 0x32是字符 3和 2的ASCII值。 repr 将直接显示可打印的ascii字符,而对不可打印的字符使用 \x00 表示法。

The numbers 0x33 & 0x32 are the ASCII values of the characters '3' and '2'. repr will show printable ascii characters directly, while using the \x00 notation for non-printable characters.

>>> b = b'\x33\x32'
>>> print b
32
>>> print repr(b)
'32'
>>> hex(ord('3'))
'0x33'

这是我

>>> def hexstr(s):
...     return '-'.join('%02x' % ord(c) for c in s)
...
>>> hexstr(b'\x00\xff\x33\x32')
'00-ff-33-32'

如果您可以继承 dict 的子类并覆盖 __ str __ 表示形式希望这种情况自动发生。

You might be able to subclass dict and override the __str__ representation if you want this to happen automatically.

这篇关于Python字节字符串在字典中打印不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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