我收到这个错误:
File "run.py", line 37, in <module>
print str1
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 24-29: ordinal not in range(256)
尝试简单地打印一些日语文本时。实际上,字符串看起来像这样:
\u5149\u66dc\u65e5\u3067\u30e9\u30c6 \u30d4\u30af\u30b7\u30fc\u4e71\u7372\u884c\u304d\u307e\u3059 \u5e0c\u671b\u8005\u52df\u96c6\u4e2d\u3067\u3059\uff3e\uff3e
来自 JSON 文件。我怎样才能打印这个?
代码:
url = "http://www.blah.com/json"
try:
result = simplejson.load(urllib2.urlopen(url))
except IOError:
print "Cannot open URL"
data = "error"
for msg in result["msg"]:
str1 = msg["character"] + " : " + msg["message"]
print str1
repr(str1) 是
u'Anys : \u5149\u66dc\u65e5\u3067\u30e9\u30c6 \u30d4\u30af\u30b7\u30fc\u4e71\u7372\u884c\u304d\u307e\u3059 \u5e0c\u671b\u8005\u52df\u96c6\u4e2d\u3067\u3059\uff3e\uff3e'
打印(sys.stdout.encoding)是
ISO-8859-1
最佳答案
您看到的错误是因为您的终端使用 latin-1 作为编码,作为旁注,您可以通过在 shell 中执行以下操作来检查终端的编码(假设它是您的标准输出):
$ python -c "import sys; print sys.stdout.encoding"
现在要以 UTF-8 打印,您应该像这样手动将字符串编码为 utf-8:
s = u"\u5149\u66dc\u65e5\u3067\u30e9\u30c6 \u30d4\u30af\u30b7\u30fc\u4e71\u7372\u884c\u304d\u307e\u3059 \u5e0c\u671b\u8005\u52df\u96c6\u4e2d\u3067\u3059\uff3e\uff3e"
print s.encode('utf-8')
#Output: 光曜日でラテ ピクシー乱獲行きます 希望者募集中です^^
关于Python: UnicodeEncodeError: 'latin-1' 编解码器无法对位置的字符进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7286968/