Issue
I'm trying to convert a string into bytes and those bytes must be in a string type. I know how to do that in pyhon3, it is pretty straight forward, but in python2 I'm just lost :(
I've tried the encode() function in python2 but it doesn't seem to work, I've read there is no such thing as byte type in python2 so that maybe the case why I'm failing.
Anyways, I wrote this code in python3 and it is working flawlessy:
>>> a="hey"
>>> b=bytes(a, 'utf-8')
>>> print(b)
b'hey'
>>> type(b)
<class 'bytes'>
>>> c=''
>>> for i in b:
... c+=str(i)+" "
...
>>>
>>> print (c)
104 101 121
Instead with python2 I've tryed, of course bytes(a, 'utf-8') but it's saying str() takes exactly one argument (2 given). Then I've tryed encode() and bytearray() but no luck with those either.
If you have any hints on how to get the representing bytes 104 101 121
of ehy
in python2, or if you know for sure that this "conversion" is not possible please let me know.
Solution
There's no need for such a conversion in Python 2, since bytes
is just an alias to str
in Python 2.
According to the documentation:
Python 2.6 adds
bytes
as a synonym for thestr
type, and it also supports theb''
notation.The 2.6
str
differs from 3.0’s bytes type in various ways; most notably, the constructor is completely different. In 3.0,bytes([65, 66, 67])
is 3 elements long, containing the bytes representingABC
; in 2.6,bytes([65, 66, 67])
returns the 12-byte string representing thestr()
of the list.The primary use of
bytes
in 2.6 will be to write tests of object type such asisinstance(x, bytes)
. This will help the2to3
converter, which can’t tell whether 2.x code intends strings to contain either characters or 8-bit bytes; you can now use eitherbytes
orstr
to represent your intention exactly, and the resulting code will also be correct in Python 3.0.
If you want the Python 3 behavior of bytes
in Python 2 in terms of being able to iterate through the bytes as integers, you can convert the string to bytearray
instead (just keep in mind that bytearray
, unlike str
and bytes
, is mutable):
>>> a = 'hey'
>>> b = bytearray(a)
>>> c = ''
>>> for i in b:
... c += str(i) + ' '
...
>>> print(c)
104 101 121
Alternatively, you can use the ord
function to convert each character to its ordinal number:
>>> for c in 'hey':
... print ord(c)
...
104
101
121
Answered By - blhsing
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.