Python2和Python3之間的str處理方式導致亂碼的講解

今天小編就爲大家分享一篇關於Python2和Python3之間的str處理方式導致亂碼的講解,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧

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的方式進行讀取 寫入會極大程度降低出現文本問題

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對神馬文庫的支持。如果你想了解更多相關內容請查看下面相關鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章