如何在我的代码中打印中文单词..使用python [英] how to print chinese word in my code.. using python

查看:82
本文介绍了如何在我的代码中打印中文单词..使用python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

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

如何我会打印'哈哈'吗?

How do I print '哈哈'?

更新:当我使用以下代码时:

Update: When I use the following code:

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

print '哈哈'

...它会打印鍝鍝

我的IDE是Ulipad,这是IDE的错误吗?

My IDE is Ulipad, is this a bug with the IDE?

第二次更新:

此代码将向右打印字符:

This code will print the characters right:

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


print u'哈哈'.encode('gb2312')

...以及当我使用此代码时:

...and when I use this:

#!/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)

...这不起作用。我应该如何正确打印变量 a

...it doesn't work. How would I print the variable a appropriately?

谢谢

推荐答案

您首先需要声明一个编码,因为错误消息说得很清楚-它甚至告诉您看起来此处了解详情!您的编码大概是 gb2312

You first need to declare an encoding, as the error messages says so clearly -- it even tells you to look here for details! Your encoding is presumably gb2312.

BTW,这样做会更简单(使用相同的编码声明)

BTW, it would be simpler (with the same encoding declaration) to do

print u'哈哈'.encode('utf-8')

,如果您的 sys.stdout,甚至可能不需要 encode 部分具有正确设置的 encoding 属性(取决于终端,操作系统等)。

and you may not even need the encode part, if your sys.stdout has an encoding attribute properly set (depends on your terminal, OS, etc).

这篇关于如何在我的代码中打印中文单词..使用python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆