迭代Python中的unicode字符串

cha*_*rpi 8 python unicode python-2.x

我遇到了使用python逐字符串地迭代unicode字符串的问题.

print "w: ",word
for c in word:
    print "word: ",c
Run Code Online (Sandbox Code Playgroud)

这是我的输出

w:  ??
word:  ? 
word:  ?
word:  ?
word:  ?
word:  ?
word:  ?
Run Code Online (Sandbox Code Playgroud)

我想要的输出是:

?
?
Run Code Online (Sandbox Code Playgroud)

当我使用len(word)时我得到6.显然每个角色都是3个unicode块.

所以,我的unicode字符串成功存储在变量中,但我无法将字符输出.我尝试过使用encode('utf-8'),decode('utf-8)和编解码器,但仍然无法获得任何好的结果.这似乎是一个简单的问题,但对我来说却是令人沮丧的.

希望有人能指出我正确的方向.

谢谢!

Pru*_*Raj 14

# -*- coding: utf-8 -*-
word = "??"
print(word)
for each in unicode(word,"utf-8"):
    print(each)
Run Code Online (Sandbox Code Playgroud)

输出:

??
?
?
Run Code Online (Sandbox Code Playgroud)

  • @charpi https://docs.python.org/2/library/codecs.html你使用`open`错误,你需要指定`encoding ='UTF-8'`.不仅仅是''UTF-8',因为你正在设置`mode`参数 (2认同)