1. 程式人生 > >【python】字串問題

【python】字串問題

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