Unicode python错误

时间:2016-08-31 21:28:17

标签: python unicode

我正在尝试打印:神奇宝贝GOViệtNam

print u"Pokémon GO Việt Nam"

我得到了:

print u"PokÚmon GO Vi?t Nam"
SyntaxError: (unicode error) 'utf8' codec can't decode byte 0xe9 in position 0: unexpected end of data

我试过了:

.encode("utf-8")
.decode("utf-8")
.decode('latin-1').encode("utf-8")
unicode(str.decode("iso-8859-4"))

我的python版本是2.7.9,Notepad ++ UTF-8编码。 没有运气,我怎么打印出来?而且我一直在遇到这种问题,调试和获得正确编码的正确方法是什么?

3 个答案:

答案 0 :(得分:4)

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

print "Pokémon GO Việt Nam"

您可以找到here更多信息

对于PyCharm设置,请转到菜单:PyCharm - >首选项然后使用搜索查找“编码”,您应该到达以下屏幕:

enter image description here

答案 1 :(得分:1)

指定编码

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

在程序的顶部

答案 2 :(得分:0)

作为替代方案,您可以对unicode字符串进行编码:

print u"Pokémon GO Việt Nam".encode('utf-8')

优点是结果字符串中的字节与源文件的编码无关:u"ệ".encode('utf-8')总是相同的3个字节"\xe1\xbb\x87"

如果你在变量中有一个unicode字符串,它也与你所做的一致。

# get text from somewhere...
text = u"Pokémon GO Việt Nam"

# assuming your terminal expects UTF-8 -- this won't work on Windows.
print text.encode('utf-8')