1. 程式人生 > >python2.x中unicode字串轉化為str字串

python2.x中unicode字串轉化為str字串

首先理解編碼encode與解碼decode

很多介面返回的資料都是unicode字串,但是我們需要轉化成str,這樣才能進行json.loads()的反序列化操作。(雖然經過我證實,有時候unicode字串也是可以直接進行反序列化操作的,但是老師說這樣更嚴謹?)

下面是將unicode編碼成為具體的字串(各種編碼格式)

unicodestring = u"Hello world" 
# 將Unicode轉化為普通Python字串:"encode"  
utf8string = unicodestring.encode("utf-8")  
asciistring = unicodestring.encode("ascii")  
isostring = unicodestring.encode("ISO-8859-1")  
utf16string = unicodestring.encode("utf-16") 

下面是將python字串解碼為unicode

# 將普通Python字串轉化為Unicode:"decode"  
plainstring1 = unicode(utf8string, "utf-8")  
plainstring2 = unicode(asciistring, "ascii")  
plainstring3 = unicode(isostring, "ISO-8859-1")  
plainstring4 = unicode(utf16string, "utf-16")  
assert plainstring1 == plainstring2 == plainstring3 == plainstring4