如何将 Python2 中的字符串转换为字节?

How to convert Strings into Bytes in Python2?

我正在尝试将字符串转换为字节,这些字节必须是字符串类型。我知道如何在 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 我试过了,当然是 bytes(a, 'utf-8') 但它说 str() 只接受一个参数(给定 2 个)。 然后我尝试了 encode() 和 bytearray() 但也没有成功。

如果您对如何获取 python2 中 ehy 的表示字节 104 101 121 有任何提示,或者如果您确定此 "conversion" 不是可能的话请告诉我。

Python 2 中不需要这样的转换,因为 bytes 只是 Python 2 中 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 3 在 Python 2 中的 bytes 行为能够将字节作为整数进行迭代,你可以将字符串转换为 bytearray 而不是(请记住 bytearraystrbytes 不同,它是可变的):

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

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

>>> for c in 'hey':
...     print ord(c)
...
104
101
121