网络编程
位置:首页>> 网络编程>> Python编程>> Python2和Python3之间的str处理方式导致乱码的讲解

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

作者:staHuri  发布时间:2022-10-01 09:46:53 

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

来源:https://blog.csdn.net/staHuri/article/details/82421044

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com