如果你想输出的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: н
>>>
是否在SO回答你的问题这个链接 - http://stackoverflow.com/questions/8873517/printing-utf-8-encoded-byte-string – Gangadhar 2012-03-27 04:31:31
或者如果它不是一个文字变量,'utf8_string.decode('utf-8')'。 – agf 2012-03-27 04:39:37