Python2和Python3之間的str處理方式導(dǎo)致亂碼的講解
Python字符串問(wèn)題
- 在arcpy中版本為 python2.x
- 在QGIS中版本為 python2.x 或者 python3.x
- python2 和python3 之間的str處理方式經(jīng)常會(huì)導(dǎo)致亂碼,故出此文
python3版本
# 將str或字節(jié)并始終返回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或字節(jié)并始終返回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的方式進(jìn)行讀取 寫入會(huì)極大程度降低出現(xiàn)文本問(wèn)題
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
Python關(guān)于實(shí)參隨形參改變而改變的問(wèn)題
本文通過(guò)實(shí)驗(yàn)總結(jié)了Python中可變和不可變數(shù)據(jù)類型的區(qū)別,并提出了通過(guò)使用.copy()方法或deepcopy()函數(shù)來(lái)保持可變數(shù)據(jù)不變的解決方案2024-11-11
python3通過(guò)udp實(shí)現(xiàn)組播數(shù)據(jù)的發(fā)送和接收操作
這篇文章主要介紹了python3通過(guò)udp實(shí)現(xiàn)組播數(shù)據(jù)的發(fā)送和接收操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05
Python?TypeError:?‘float‘?object?is?not?subscriptable錯(cuò)
發(fā)現(xiàn)問(wèn)題寫python的時(shí)候出現(xiàn)了這個(gè)錯(cuò),所以想著給大家總結(jié)下,這篇文章主要給大家介紹了關(guān)于Python?TypeError:?‘float‘?object?is?not?subscriptable錯(cuò)誤的解決辦法,需要的朋友可以參考下2022-12-12
Pandas常用的數(shù)據(jù)結(jié)構(gòu)和常用的數(shù)據(jù)分析技術(shù)
Pandas是Python中用于數(shù)據(jù)處理和分析的強(qiáng)大庫(kù),其最常用的數(shù)據(jù)結(jié)構(gòu)是Series和DataFrame。Series類似于一維數(shù)組,可以表示一列數(shù)據(jù);DataFrame類似于二維表格,可以表示多列數(shù)據(jù)2023-04-04
200行python代碼實(shí)現(xiàn)2048游戲
這篇文章主要為大家詳細(xì)介紹了200行Python代碼實(shí)現(xiàn)2048游戲,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07

