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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值