我试图把一个字符串转换成字节,这些字节必须是字符串类型。我知道如何在pyhon3中做到这一点,这是非常直截了当的,但在python2中我只是迷失了:(
我尝试过python2中的encode()函数,但它似乎不起作用,我读到python2中没有字节类型这样的东西,所以可能就是我失败的原因。在
总之,我用python3编写了这段代码,它运行得非常完美:
>>> 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
相反,我尝试了python2,当然是字节(a,'utf-8'),但它的意思是str()只接受一个参数(给定2个)。 然后我尝试了encode()和bytearray(),但这两种方法都不太好用。在
如果您有任何关于如何获得python2中ehy
的表示字节104 101 121
的提示,或者如果您确定这个“转换”是不可能的,请告诉我。在
在python2中不需要这样的转换,因为
bytes
只是python2中str
的别名。在根据documentation:
如果您希望Python 2中}和{}不同,它是可变的):
bytes
的python3行为能够以整数的形式迭代字节,那么可以将字符串转换为bytearray
(只需记住,bytearray
与{或者,可以使用
^{pr2}$ord
函数将每个字符转换为其序号:相关问题 更多 >
编程相关推荐