简体   繁体   English

Python3 和 ASCII

[英]Python3 and ASCII

I am learning python, and I am a bit confused about contents.encode() in init() in the following code.我正在学习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')

Python 3 strings are Unicode strings. Python 3 字符串是 Unicode 字符串。 There are situations where you want data in a byte string, where (typically) every character is a single byte.在某些情况下,您需要字节字符串中的数据,其中(通常)每个字符都是一个字节。 "string".encode('ascii') creates a byte string containing the six ASCII characters s, t, r, i, n, g out of the Unicode string containing these characters as Unicode. "string".encode('ascii')从包含这些字符的 Unicode 字符串中创建一个字节字符串,其中包含六个 ASCII 字符 s, t, r, i, n, g 。

This is a portability tweak;这是一个便携性调整; Python 2 strings were byte strings (though there is the u"string" notation for creating Unicode strings, starting in Python 2.5 IIRC). Python 2 字符串是字节字符串(尽管从 Python 2.5 IIRC 开始,有用于创建 Unicode 字符串的u"string"表示法)。

For a richer exposition of the precise difference, perhaps see http://nedbatchelder.com/text/unipain.html有关精确差异的更丰富的说明,请参阅http://nedbatchelder.com/text/unipain.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM