Python3 和 ASCII

4 python ascii character-encoding python-3.x

我正在学习python,我对以下代码中init()中的contents.encode()有点困惑。

PY3 = sys.version_info[0] > 2


class Test:
    def __init__(self):
        self.contents = ''
        if PY3:
            self.contents = self.contents.encode('ascii')
Run Code Online (Sandbox Code Playgroud)

tri*_*eee 5

Python 3 字符串是 Unicode 字符串。在某些情况下,您需要字节字符串中的数据,其中(通常)每个字符都是单个字节。"string".encode('ascii')从包含 6 个 ASCII 字符 s、t、r、i、n、g 的 Unicode 字符串中创建包含这些字符的 Unicode 字节字符串。

这是一个可移植性调整;Python 2 字符串是字节字符串(尽管u"string"从 Python 2.5 IIRC 开始有创建 Unicode 字符串的表示法)。

有关精确差异的更丰富的说明,也许请参阅http://nedbatchelder.com/text/unipain.html