温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python2和Python3之间的str处理方式导致乱码怎么办

发布时间:2021-07-13 15:54:23 来源:亿速云 阅读:98 作者:小新 栏目:开发技术

这篇文章主要介绍了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和Python3之间的str处理方式导致乱码怎么办”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI