2012-03-27 326 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

相关问题