2

Python2: [d for d in b'abc'] --> ['a', 'b', 'c']

Python3: [d for d in b'abc'] --> [97, 98, 99]

How can I loop over bytes in Python3 and each iteration should get a byte string containing one character (like Python2 did)?

guettli
  • 25,042
  • 81
  • 346
  • 663

3 Answers3

1

This will work

[chr(d) for d in b'abc']

Result

['a', 'b', 'c']
Deepstop
  • 3,627
  • 2
  • 8
  • 21
1

You need to convert the byte-string to normal string in Python 3.

[d for d in b'abc'.decode()]

Should return ['a', 'b', 'c']

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
-1

You can simply convert the integers back to strings:

[chr(d) for d in b'abc'] --> ['a', 'b', 'c']

Or even to bytes:

[chr(d).encode() for d in b'abc'] --> [b'a', b'b', b'c']
user38
  • 151
  • 1
  • 14