python 字典转字符串字节过大_Python字节字符串在字典中打印不正确

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)

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

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.

解决方案

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'}

EDIT

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'

Here's a function that I use for printing hex representations of strings

>>> def hexstr(s):

... return '-'.join('%02x' % ord(c) for c in s)

...

>>> hexstr(b'\x00\xff\x33\x32')

'00-ff-33-32'

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值