2014-02-16 124 views
12

究竟是一個unicode字符串?什麼是unicode字符串?

什麼是普通字符串和unicode字符串之間的區別?

什麼是UTF-8?

我想學習Python,現在,我不斷聽到這個流行語。下面的代碼是做什麼的?

I18N字符串(Unicode)的

> ustring = u'A unicode \u018e string \xf1' 
> ustring 
u'A unicode \u018e string \xf1' 

## (ustring from above contains a unicode string) 
> s = ustring.encode('utf-8') 
> s 
'A unicode \xc6\x8e string \xc3\xb1' ## bytes of utf-8 encoding 
> t = unicode(s, 'utf-8')    ## Convert bytes back to a unicode string 
> t == ustring      ## It's the same as the original, yay! 
True 

文件的Unicode

import codecs 

f = codecs.open('foo.txt', 'rU', 'utf-8') 
for line in f: 
# here line is a *unicode* string 
+2

互聯網搜索可能是一個很好的開始.... –

+0

可能重複的[Unicode在Python](http://stackoverflow.com/questions/8277277/unicode-in-python) – tripleee

+0

另請參見http: //bit.ly/unipain – tripleee

回答

23

這個答案是關於Python 2.在Python 3中,str是一個Unicode字符串。

Python的str類型是8位字符集。英文字母表可以用這些8位字符表示,但符號如±,♠,Ω和ℑ不能。

的Unicode是用於具有寬範圍的字符工作的標準。每個符號都有一個代碼點(一個數字),並且可以使用各種編碼對這些代碼點進行編碼(轉換爲字節序列)。

UTF-8就是這樣的一個編碼。低碼點使用一個字節進行編碼,較高的碼點編碼爲字節序列。

Python的unicode類型碼點的集合。行ustring = u'A unicode \u018e string \xf1'創建一個包含20個字符的Unicode字符串。

當Python解釋器顯示的值爲ustring時,它會轉義兩個字符(Ǝ和ñ),因爲它們不在標準的可打印範圍內。

s = unistring.encode('utf-8')編碼使用UTF-8 Unicode字符串。這將每個代碼點轉換爲適當的字節或字節序列。結果是一組字節,它以str的形式返回。的s大小是22個字節,因爲兩個字符具有高的碼點和被編碼爲兩個字節的序列而不是單個字節。

當Python解釋顯示的s值時,它逸出不在可打印範圍(\xc6\x8e\xc3,和\xb1)四個字節。兩對的字節不被視爲單個字符,如之前因爲s是類型str,不unicode的。

t = unicode(s, 'utf-8')確實的encode()相反。它通過查看s的字節並解析字節序列來重構原始碼點。結果是一個Unicode字符串。

codecs.open()的調用指定utf-8作爲編碼,它告訴Python將文件內容(字節集合)解釋爲使用UTF-8編碼的Unicode字符串。

+2

更具體地說,上述對於Python v2是正確的。在Python v3中,Unicode字符串是默認的。 – tripleee

-4

Python支持字符串類型和Unicode類型。一個字符串是一串字符,而一個unicode是一串「指針」。的unicode是序列的內存中表示並在其上每個符號是不旨在選擇在地圖中的炭炭但一些(十六進制格式)。 所以unicode var沒有編碼,因爲它不包含字符。

+0

您可以在此博客上詳細瞭解它 http://www.carlosble.com/2010/12/understanding-python-and-unicode/ –

+2

-1不是一個準確的答案。那些不是「指針」,兩種類型都用來表示字符串。 – tripleee