瞭解python中bytes,str和unicode的區別
阿新 • • 發佈:2019-02-12
首先來說把Unicode轉換為為原始8位值(二進位制資料),有很多種辦
編寫Python程式的時候,核心部分應該用Unicode來寫,也就是python3中的str,python2中的unicode
python3中2種表示字元序列的型別:bytes和str
前者的例項包含了原始8位值,後者的例項包含了Unicode字元
python3中接受bytes和str,並總是返回str:
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
return bytes_or_str.decode('utf-8' )
return bytes_or_str
python3中接受bytes和str,並總是返回bytes:
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, str):
return bytes_or_str.encode('utf-8')
return bytes_or_str
python2中2種表示字元序列的型別:unicode和str
與python3剛好相反:後者的例項包含了原始8位值,前者的例項包含了Unicode字元
python2中接受unicode和str,並總是返回unicode:
def to_str(bytes_or_str):
if isinstance(bytes_or_str, str):
return bytes_or_str.decode('utf-8')
return bytes_or_str
python2中接受unicode和str,並總是返回str:
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, unicode):
return bytes_or_str.encode('utf-8' )
return bytes_or_str
python2和python3需要注意的事情
1.python2中如果str只包含7位的ASCII字元,那麼unicode和str 就是同一種類型,可以+操作
2.python3內建的open函式獲取檔案控制代碼,預設採用utf-8的格式操作檔案,python2則預設是二進位制
python2 的寫法:
with open("/temp/file.bin",'w')as f :
f.write(os.urandom(10))
python3 的寫法:
with open("/temp/file.bin",'wb')as f :
f.write(os.urandom(10))
ps:如何讓你的程式碼pythonic