• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

代码总结Python2 和 Python3 字符串的区别

python 搞代码 4年前 (2022-01-07) 18次浏览 已收录 0个评论

在本篇文章里小编给大家整理的是一篇关于Python2 和 Python3 字符串的区别以及实例代码,需要的朋友们学习下。

Python2

 >>> >>> isinstance(b'abc', bytes) True >>> >>> isinstance(b'abc', str) True >>> >>> isinstance('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', bytes) True >>> >>> isinstance(b'abc', str) False >>> >>> isinstance('abc', str) True >>> >>> isinstance('abc', bytes) False >>> >>> >>> >>> 'abc'.startswith('ab') True >>> >>> b'abc'.startswith('ab'.encode()) True >>> >>> b'abc'.startswith('ab') Traceback (most recent call last): File "", line 1, in  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 "", line 1, in  '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') =<div style="color:transparent">来源gaodai^.ma#com搞#代!码网</div>> byte型

以上就是相关的知识点内容,如果大家有任何补充可以联系gaodaima搞代码网小编。

以上就是代码总结Python2 和 Python3 字符串的区别的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:代码总结Python2 和 Python3 字符串的区别

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址