这是我的代码:
print '??'.decode('gb2312').encode('utf-8')
Run Code Online (Sandbox Code Playgroud)
...它打印:
SyntaxError: Non-ASCII character '\xe5' in file D:\zjm_code\a.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
Run Code Online (Sandbox Code Playgroud)
我该如何打印'哈哈'?
更新: 当我使用以下代码时:
#!/usr/bin/python
# -*- coding: utf-8 -*-
print '??'
Run Code Online (Sandbox Code Playgroud)
...打印???.这不是我想要的.
我的IDE是Ulipad,这是IDE的错误吗?
第二次更新:
此代码将正确打印字符:
#!/usr/bin/python
# -*- coding: utf-8 -*-
print u'??'.encode('gb2312')
Run Code Online (Sandbox Code Playgroud)
......当我用它时:
#!/usr/bin/python
# -*- coding: utf-8 -*-
a='??'
print a.encode('gb2312')
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 5, in <module>
print a.encode('gb2312')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
...要么...
#!/usr/bin/python
# -*- coding: utf-8 -*-
a='??'
print unicode(a).encode('gb2312')
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 5, in <module>
print unicode(a).encode('gb2312')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
......它不起作用.我该如何a正确打印变量?
谢谢
Ale*_*lli 11
你首先需要声明的编码,作为错误信息说得很清楚-它甚至会告诉你看看这里的细节!大概是你的编码gb2312.
顺便说一下,它会更简单(使用相同的编码声明)
print u'??'.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)
encode如果您sys.stdout的encoding属性设置正确(取决于您的终端,操作系统等),您可能甚至不需要该部件.
需要指定python源代码文件的编码,这里是utf-8的编码。它位于 python 解释器路径下方的右上角。
#!/usr/bin/python
# -*- coding: utf-8 -*-
Run Code Online (Sandbox Code Playgroud)
如果您转到错误消息中的 url,您可以找到有关指定 python 源文件编码的更多信息。
一旦指定了源文件的编码,您就不必对文本进行解码。