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

Python2和Python3之间的str处理方式导致乱码的讲解

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

今天小编就为大家分享一篇关于Python2和Python3之间的str处理方式导致乱码的讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

Python字符串问题

  1. 在arcpy中版本为 python2.x
  2. 在QGIS中版本为 python2.x 或者 python3.x
  3. python2 和python3 之间的str处理方式经常会导致乱码,故出此文

python3版本

 # 将str或字节并始终返回str def to_str(bytes_or_str): if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode(‘utf-8') else: value = bytes_or_str return value # 将str或字节并始终返回bytes def to_bytes(bytes_or_str): if isinstance(bytes_or_str, str): value = bytes_or_str.encode(‘utf-8') else: value = bytes_or_str return value

python2版本

– 在python2版本中使用unicode方式

 # 接受str或unicode,并总是返回unicode def to_unicode(unicode_or_str): if isinstance(unicode_or_str, str): value = unicode_or_str.decode(‘utf-8') else: value = unicode_or_str return value # 接受str或unicode,并总是返回str def to_str(unicode_or_str): if isinstance(unicode_or_str, unicode): value = unicode_or_str.encode(‘utf-8') else: value = unicode_or_str return value

备注

在python中不管任何版本,都是用 bytes的方式进行读取 写入会极大程度降低出现文本问题

总结

以上就是Python2和Pyt来源gaodai#ma#com搞@@代~&码*网hon3之间的str处理方式导致乱码的讲解的详细内容,更多请关注gaodaima搞代码网其它相关文章!


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

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

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

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

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