程式碼總結Python2 和 Python3 字串的區別
阿新 • • 發佈:2020-02-01
Python2
>>> >>> isinstance(b'abc',bytes) True >>> >>> isinstance(b'abc',str) True >>> >>> isinstance('abc',bytes) True >>> >>> >>> >>> 'abc'.startswith('ab') True >>> >>> b'abc'.startswith('ab'.encode()) True >>> >>> b'abc'.startswith('ab') True >>> >>> 'abc'.startswith('ab'.encode()) True >>>
Python3
>>> >>> isinstance(b'abc',str) False >>> >>> isinstance('abc',bytes) False >>> >>> >>> >>> 'abc'.startswith('ab') True >>> >>> b'abc'.startswith('ab'.encode()) True >>> >>> b'abc'.startswith('ab') Traceback (most recent call last): File "<pyshell#25>",line 1,in <module> b'abc'.startswith('ab') TypeError: startswith first arg must be bytes or a tuple of bytes,not str >>> >>> 'abc'.startswith('ab'.encode()) Traceback (most recent call last): File "<pyshell#27>",in <module> 'abc'.startswith('ab'.encode()) TypeError: startswith first arg must be str or a tuple of str,not bytes >>>
擴充套件學習
python2中有一種型別叫做unicode型,例
type(u"a") => str型 type("a".decode('utf8')) => unicode型
兩者返回的型別都是unicode型
而在python3中,所有的字串都是unicode,所以就不存在單獨的unicode型,全部都是字串型
type(u"a") => str型 type("a".decode('utf8')) => 報錯,python3不能這樣寫
但是python3中多處一種字串
type(b'132') => byte型
以上就是相關的知識點內容,如果大家有任何補充可以聯絡我們小編。