In Python 2:
import struct
struct.pack('B', 21)[0] # returns '\x15'
In Python 3:
import struct
struct.pack('B', 21)[0] # returns 21
Is there some way to create the byte string returned by Python 2 in Python 3? Any pointers would be greatly appreciated!
asked May 30, 2020 at 18:42
duhaime
27.9k22 gold badges197 silver badges243 bronze badges
1 Answer 1
Just don't index the byte string it returns:
>>> struct.pack('B', 21)
b'\x15'
answered May 30, 2020 at 18:45
orlp
119k39 gold badges226 silver badges325 bronze badges
Sign up to request clarification or add additional context in comments.
9 Comments
orlp
@duhaime That's what you wrote, the first byte is 21. Clearly you are looking for something else.
orlp
@duhaime Are you looking for
hex(21) or "{:x}".format(21)?orlp
@duhaime Getting the hexadecimal representation of an integer as a string is a way different question that you originally asked though.
duhaime
I cleaned up some of my comments but wanted to ask--this is a bytes data type, whereas Python 2 returns a string--can one get this object as a string type in Python 3?
chr(21) returns the string that's neededorlp
@duhaime That is not a valid string for all values you can give to the
struct.pack. You will have to change the other code to work with bytes instead of strings. |
Explore related questions
See similar questions with these tags.
default
chr(21)!packreturns a string and each member of a string is a single character string. In python 3,packquite sensibly returns a bytes array but individual members of a bytes array are ints < 256. Its a place where 2 to 3 conversion could break. By "member", I mean the value you get when you index an item.packis an opaque blob. You get the right stuff back when you unpack. When I wrote my comment I wasn't sure the use case of python ever touching a member of the blob. I'm still not sure I've got one.for b in data:myconnection.send(b).