这是我的代码: print '哈哈'.decode('gb2312').encode('utf-8') …它打印: 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 det
print '哈哈'.decode('gb2312').encode('utf-8')
…它打印:
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
我该如何打印’哈哈’?
更新:当我使用以下代码时:
#!/usr/bin/python # -*- coding: utf-8 -*- print '哈哈'
…打印鍝埚搱.这不是我想要的.
我的IDE是Ulipad,这是IDE的错误吗?
第二次更新:
此代码将正确打印字符:
#!/usr/bin/python # -*- coding: utf-8 -*- print u'哈哈'.encode('gb2312')
……当我用它时:
#!/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)
…要么…
#!/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)
……它不起作用.如何正确打印变量?
谢谢
您首先需要声明一个编码,因为错误消息说得很清楚 – 它甚至会告诉您查看 here以获取详细信息!你的编码大概是gb2312.顺便说一下,它会更简单(使用相同的编码声明)
print u'哈哈'.encode('utf-8')
如果你的sys.stdout正确设置了编码属性(取决于你的终端,操作系统等),你可能甚至不需要编码部分.