Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

cjk - how to print chinese word in my code.. using python

This is my code:

print '哈哈'.decode('gb2312').encode('utf-8')

...and it prints:

SyntaxError: Non-ASCII character 'xe5' in file D:zjm_codea.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 '哈哈'

... it prints 鍝堝搱. That isn't what I wanted to get.

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

Second Update:

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_codea.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)

...or...

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

a='哈哈'
print unicode(a).encode('gb2312')
Traceback (most recent call last):
  File "D:zjm_codea.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)

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

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, it would be simpler (with the same encoding declaration) to do

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

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...