Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing string to byte type in Python 2.7

In python 3.2, i can change the type of an object easily. For example :

x=0
print(type (x))
x=bytes(0)
print(type (x))

it will give me this :

<class 'int'>
<class 'bytes'>

But, in python 2.7, it seems that i can't use the same way to do it. If i do the same code, it give me this :

<type 'int'>
<type 'str'>

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

like image 564
Smith Avatar asked May 30 '12 10:05

Smith


People also ask

How do you turn a string into a byte?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument.

Is byte [] same as string?

Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.

What does byte () do in Python?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.

Is there a byte type in Python?

Python supports a range of types to store sequences. There are six sequence types: strings, byte sequences (bytes objects), byte arrays (bytearray objects), lists, tuples, and range objects.


2 Answers

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.

like image 168
Martijn Pieters Avatar answered Sep 21 '22 04:09

Martijn Pieters


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
like image 29
Belial Avatar answered Sep 19 '22 04:09

Belial