今天小編就爲大家分享一篇關於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的方式進行讀取 寫入會極大程度降低出現文本問題
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對神馬文庫的支持。如果你想了解更多相關內容請查看下面相關鏈接