我正在学习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')发布于 2016-07-20 01:50:38
Python 3字符串是Unicode字符串。在某些情况下,您需要字节字符串形式的数据,其中(通常)每个字符都是一个字节。"string".encode('ascii')在Unicode字符串中创建一个字节字符串,其中包含六个ASCII码字符s,t,r,i,n,g,这些字符都是Unicode。
这是一个可移植性调整;Python2字符串是字节字符串(尽管从Python2.5IIRC开始,有用于创建Unicode字符串的u"string"表示法)。
有关精确区别的更丰富的说明,请参阅http://nedbatchelder.com/text/unipain.html
https://stackoverflow.com/questions/38465194
复制相似问题