Home > Software design >  int to chr conversion behaving differently in loop or script
int to chr conversion behaving differently in loop or script

Time:10-08

I have array of ints which needs to be converted into string or byte string but its behaving different when I run in script vs in cli/repel. also same behavior when run via for loop it only encoding few of them or showing few of them.

Python 3.9.6 (default, Jul 19 2021, 05:27:44) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> arr = [151, 131, 104, 216, 60, 135]
>>> list(map(chr, arr))
['\x97', '\x83', 'h', 'Ø', '<', '\x87']
>>> ''.join(list(map(chr, arr)))
'\x97\x83hØ<\x87'
>>> for item in arr:
...     print(chr(item))
... 


h
Ø
<

>>> 

Same thing i get when I print in script. hØ< only

int array to chr string

CodePudding user response:

The list.__str__ shows the repr representation of its elements, not their str representation. The same goes for the interactive interpreter when just displaying any expression. Hence the difference:

arr = [151, 131, 104, 216, 60, 135]
''.join(map(chr, arr))  # interpreter shows repr(expr)
# '\x97\x83hØ<\x87'
print(''.join(map(chr, arr)))  # print prints str(expr)
# hØ<

The

list(map(chr, arr))
# ['\x97', '\x83', 'h', 'Ø', '<', '\x87']

makes sense because the repr gives you more information of the elements. Imagine [1, 2, 3] vs ["1", "2", "3"] vs ["1", "2, 3"]. They would look identical if list.__str__ showed the str representations.

  • Related