【问题标题】:Unicode python ErrorUnicode python 错误
【发布时间】:2016-08-31 21:28:17
【问题描述】:

我正在尝试打印:Pokémon GO Việt Nam

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编码。 没有运气,我该如何打印它?而且我一直遇到这种问题,调试和获得正确编码的正确方法是什么?

【问题讨论】:

  • 你用的是什么版本的python?我使用 python 3.5 打印了这个,效果很好。
  • 您是在输入它还是从其他来源获取它?在我的操作系统上,从 SO 复制和粘贴会在 2.7 和 3.5 上产生正确的结果。
  • 使用 Python 3+ 将打印作为函数工作
  • 我的python版本是2.7.9

标签: python unicode


【解决方案1】:
#!/usr/bin/python
# -*- coding: utf-8 -*-

print "Pokémon GO Việt Nam"

你可以找到here更多信息

对于 PyCharm 设置,进入菜单:PyCharm --> Preference 然后使用搜索查找“编码”,您应该会到达以下屏幕:

【讨论】:

  • 是的,也可以试试,如果我们只打印 u"pokémon" 而不是 "Pokémon GO Việt Nam" 就可以了
  • @BrendaMartinez:您的编辑器使用什么编码?
  • @BrendaMartinez 确保您的 IDE 编码和项目编码都设置为 'utf-8'
  • Utf-8 ,记事本++
  • @BrendaMartinez 以及 notepad++ 是另一个问题 :) 使用合适的 IDE,例如 PyCharm:您将获得 IDE 的所有好处,例如调试和检查功能以及许多其他好处。
【解决方案2】:

指定编码

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

在程序顶部

【讨论】:

  • 是的,也试过了,如果我们只打印 u"pokémon" 而不是 "Pokémon GO Việt Nam" 就可以了
【解决方案3】:

作为替代方案,您可以对 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')

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 2021-09-01
    • 2011-03-14
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多