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

yipeiwu_com6年前Python基础

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

Python安装模块的常见问题及解决方法

1、error: command ‘x86_64-linux-gnu-gcc' failed with exit status 解决办法: # Python 3 $ sudo apt...

介绍Python的Django框架中的静态资源管理器django-pipeline

 django-pipeline 是一个 Django 下非常方便的静态资源管理 app,尤其是 1.2 版本之后,利用 django-staticfiles 的collect...

浅谈python socket函数中,send与sendall的区别与使用方法

在python socket编程中,有两个发送TCP的函数,send()与sendall(),区别如下: socket.send(string[, flags])  发送TCP数据,返回...

Python中获取对象信息的方法

当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type()判断: >...

利用Python自带PIL库扩展图片大小给图片加文字描述的方法示例

利用Python自带PIL库扩展图片大小给图片加文字描述的方法示例

前言 最近的一个项目中需要在图片上添加文字,使用了OpenCV,结果发现利用opencv给图像添加文字有局限。可利用的字体类型比较少,需要安装Freetype扩展,比较复杂。而且不能用p...