如何在Python2中将字符串转换成字节?

2024-09-28 20:56:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图把一个字符串转换成字节,这些字节必须是字符串类型。我知道如何在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的提示,或者如果您确定这个“转换”是不可能的,请告诉我。在


Tags: 函数字符串代码类型字节bytes原因python3
1条回答
网友
1楼 · 发布于 2024-09-28 20:56:40

在python2中不需要这样的转换,因为bytes只是python2中str的别名。在

根据documentation

Python 2.6 adds bytes as a synonym for the str type, and it also supports the b'' 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 representing ABC; in 2.6, bytes([65, 66, 67]) returns the 12-byte string representing the str() of the list.

The primary use of bytes in 2.6 will be to write tests of object type such as isinstance(x, bytes). This will help the 2to3 converter, which can’t tell whether 2.x code intends strings to contain either characters or 8-bit bytes; you can now use either bytes or str to represent your intention exactly, and the resulting code will also be correct in Python 3.0.

如果您希望Python 2中bytes的python3行为能够以整数的形式迭代字节,那么可以将字符串转换为bytearray(只需记住,bytearray与{}和{}不同,它是可变的):

>>> a = 'hey'
>>> b = bytearray(a)
>>> c = ''
>>> for i in b:
...     c += str(i) + ' '
...
>>> print(c)
104 101 121

或者,可以使用ord函数将每个字符转换为其序号:

^{pr2}$

相关问题 更多 >