Changing string to byte type in Python 2.7

牧云@^-^@ 提交于 2019-11-28 12:03:34

What can i do to change the type into a bytes type?

You can't, there is no such type as 'bytes' in Python 2.7.

From the Python 2.7 documentation (5.6 Sequence Types): "There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects."

From the Python 3.2 documentation (5.6 Sequence Types): "There are six sequence types: strings, byte sequences (bytes objects), byte arrays (bytearray objects), lists, tuples, and range objects."

You are not changing types, you are assigning a different value to a variable.

You are also hitting on one of the fundamental differences between python 2.x and 3.x; grossly simplified the 2.x type unicode has replaced the str type, which itself has been renamed to bytes. It happens to work in your code as more recent versions of Python 2 have added bytes as an alias for str to ease writing code that works under both versions.

In other words, your code is working as expected.

In Python 2.x, bytes is just an alias for str, so everything works as expected. Moreover, you are not changing the type of any objects here – you are merely rebinding the name x to a different object.

May be not exactly what you need, but when I needed to get the decimal value of the byte d8 (it was a byte giving an offset in a file) i did:

a = (data[-1:])          # the variable 'data' holds 60 bytes from a PE file, I needed the last byte
                         #so now a == '\xd8'  , a string
b = str(a.encode('hex')) # which makes b == 'd8' , again a string
c = '0x' + b             # c == '0xd8' , again a string
int_value = int(c,16)    # giving me my desired offset in decimal: 216

                         #I hope this can help someone stuck in my situation
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!