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
  • 23,964
  • 63
  • 293
  • 556

3 Answers3

2

This will work

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

Result

['a', 'b', 'c']
Deepstop
  • 3,314
  • 2
  • 6
  • 20
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,230
  • 10
  • 37
  • 68
0

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
  • 133
  • 1
  • 13