使用unicode 處理國際化文字
任務:需要處理包含非ascii字元的字串
解決
>>> german_ae = unicode('xc3\xa4
','utf8')
'''german_ae 是乙個unicode字串 根據指定的utf-8編碼方式,通過解析單位元組字串xc3\xa4 建立了乙個unicode字串
然後就可以像處理其他字串一樣處理unicode字串
'''>>>sentence = '
this is a
' +german_ae
>>>sentence2 = "
easy!
">>>para = ". "
,join([sentence,sentence2])
#sentence 和 para 都是unicode字串 因為其他字串和unicode字串之間的操作總會產生unicode字串
為了避免unicodedecodeerror異常 ,開發者總結了兩條規律
2 在unicode和普通字串之間轉換
unicodestring = u'hello world'#
將unicode轉化為普通python字串:"encode"
utf8string = unicodestring.encode("
utf-8")
ascstring = unicodestring.encode("
ascii")
#將普通python字串轉化為unicode:"decode"
plainstring = unicode(utf8string,"
utf-8")
plainstring1 = unicode(ascstring,"
ascii
")
python字元編碼
ascii 碼是乙個位元組,通常只能顯示英文本母和數字。unicode碼為了顯示多種語言產生,但是要占用兩個位元組,顯示文字要占用大量空間 utf 8 為了節約空間而生,英文本元只用乙個位元組儲存,中文字元需要三個位元組 character ascii unicode utf 8 a01000000...
python字元編碼
列印python檔案編碼 import sys print sys.getdefaultencoding 中文的乙個字元unicode占用2個位元組。對在於ascii字元占用1個位元組 utf 8中 中文字元佔3個位元組,英文本元占用1個位元組 編碼和轉碼 unicode不能再解碼了 它是基層的 u...
Python字元編碼
在用python程式設計中,字串有兩種表示方法 string 和 u string 為什麼字串要是用這兩種表達方式。不是僅僅用前一種呢?使用type 函式檢視,它們各自是str物件和unicode物件。這兩個物件有什麼差別嗎?還有經經常使用到的encode 和decode 又是幹什麼的呢?都說pyt...