美文网首页扣丁学堂Python培训
扣丁学堂Python培训简述如何解决Python2和Python

扣丁学堂Python培训简述如何解决Python2和Python

作者: 994d14631d16 | 来源:发表于2019-03-21 17:17 被阅读0次

  Python2和Python3之间的str处理方式导致乱码后应该怎么办呢?本篇文章扣丁学堂Python培训小编给小伙伴分享一下如何解决Python2和Python3之间的str处理方式导致乱码问题,文中有代码列出供大家参考,现在分享给大家,具有很好的参考价值,希望对小伙们有帮助。

Python字符串问题:

在arcpy中版本为 python2.x

在QGIS中版本为 python2.x 或者 python3.x

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的方式进行读取 写入会极大程度降低出现文本问题。

  想要了解更多关于Python开发方面内容的小伙伴,请关注扣丁学堂Python培训官网、微信等平台,扣丁学堂IT职业在线学习教育有专业的Python讲师为您指导,此外扣丁学堂老师精心推出的Python视频教程定能让你快速掌握Python从入门到精通开发实战技能。

【关注微信公众号获取更多学习资料】   

      【扫码进入Python全栈开发免费公开课】

相关文章

网友评论

    本文标题:扣丁学堂Python培训简述如何解决Python2和Python

    本文链接:https://www.haomeiwen.com/subject/kvucvqtx.html