2012-03-27 323 views
1

我讀了很多鏈接和建議,畢竟我更加困惑,然後我需要在Python中處理不是ASCII字符的字符串。枚舉utf-8字符串最簡單的方法

我使用Python 2.7在Ubuntu:

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

for i, j in enumerate('Сон'): print '%d: %s' % (i+1, j) 

輸出:

1: Ð 
2: ¡ 
3: Ð 
4: ¾ 
5: Ð 
6: ½ 

什麼是最簡單的方法我得到3 UTF-8編碼的字符枚舉,而不是6個字節字符?

+0

是否在SO回答你的問題這個鏈接 - http://stackoverflow.com/questions/8873517/printing-utf-8-encoded-byte-string – Gangadhar 2012-03-27 04:31:31

+0

或者如果它不是一個文字變量,'utf8_string.decode('utf-8')'。 – agf 2012-03-27 04:39:37

回答

1

添加一個 'U' 在它前面指定它是unicode:

for i, j in enumerate(u'Сон'): print '%d: %s' % (i+1, j) 

輸出

1: С 
2: о 
3: н 
+0

@theta,'sys.stdout.encoding'說什麼? – 2012-03-27 04:37:32

+0

我已經試過這個,現在因爲我有兩個類似的答案,並檢查了更多 - 問題是我的編輯器 - SciTE和它的輸出窗格。在終端你的建議工作正常,並在SciTE(我工作最)我得到UnicodeDecodeError。將進一步調查 – theta 2012-03-27 04:38:25

3

簡單的回答:don't

>>> len(u'Сон') 
3 
+1

我之前瀏覽過它 - 提前解碼,稍後編碼。沒有得到它,並且希望Python 3早於預期 – theta 2012-03-27 04:40:59

+1

@theta Eh? Python 3.0於2008年12月發佈。 – 2012-03-27 05:13:08

+0

你最喜歡的Python包是否支持它,或者你的系統將它設置爲默認解釋器:D – theta 2012-03-27 05:35:47

1
# -*- coding: utf-8 -*- 
for i, j in enumerate(u'Сон'): 
    print '%d: %s' % (i+1, j) 

關於源代碼的編碼在Python:http://www.python.org/dev/peps/pep-0263/

'''pre'

'u'pre在string之前修複意味着將使用unicode字符串。

3

如果你想輸出的UTF-8字符,你還需要確保Python知道使用哪種編碼

$ export PYTHONIOENCODING=ascii 
$ python 
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import sys 
>>> sys.stdout.encoding 
'ascii' 
>>> for i, j in enumerate(u'Сон'): print '%d: %s' % (i+1, j) 
... 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0421' in position 3: ordinal not in range(128) 

$ export PYTHONIOENCODING=utf-8 
$ python 
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import sys 
>>> sys.stdout.encoding 
'utf-8' 
>>> for i, j in enumerate(u'Сон'): print '%d: %s' % (i+1, j) 
... 
1: С 
2: о 
3: н 
>>> 
+0

謝謝,所提到的問題是我的編輯。它的輸出窗格可能是ascii,但如果您熟悉SciTE,則將其設置爲「output.code.page = 65001」 – theta 2012-03-27 04:46:19

相關問題