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

yipeiwu_com5年前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 4.0 预计推出的新功能

Python 3.8 发布在即,核心开发者团队让我总结一下最近讨论的 Python 4.0 预计推出的新功能,代码名为“ Ouroboros:自噬蛇”。Python 4.0 是大家翘首以...

Python中endswith()函数的基本使用

函数:endswith() 作用:判断字符串是否以指定字符或子字符串结尾,常用于判断文件类型 相关函数:判断字符串开头 startswith() 一、函数说明 语法:string.en...

完美解决Pycharm无法导入包的问题 Unresolved reference

完美解决Pycharm无法导入包的问题 Unresolved reference

如下所示: Unresolved reference 'ERROR_CODE_INPUT_ERROR' less... (Ctrl+F1) This inspection dete...

python多维数组切片方法

1、数组a第0个元素(二维数组)下的所有子元素(一维数组)的第一列 import numpy as np b=np.arange(24) a=b.reshape(2,3,4) pri...

解决Python 中英文混输格式对齐的问题

Python中使用str.format进行格式化输出 format使用方法较多,这里只说明其在填充与对齐上的使用方法: 填充与对齐 填充常跟对齐一起使用 ^、<、>分别是居中...