Python byte string print incorrectly in dictionary

后端 未结 1 951
别那么骄傲
别那么骄傲 2021-01-24 08:16

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)


        
相关标签:
1条回答
  • 2021-01-24 08:38

    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)
提交回复
热议问题