tags:

views:

102

answers:

3

this is my code:

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

and it print :

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 to print '哈哈'

thanks

updated when i use this:

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

print '哈哈'

it print

鍝堝搱

that is not i want get .

and i ide is ulipad , is the ide's bug ?

updated2

this code can print 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)

or

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

so how to print right when use ' a '

thanks

+2  A: 

You need to specify the encoding of the python source code file, here is the coding for utf-8. It goes at the top right underneath the path the the python interpreter.

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

If you go to the url in the error message you can find more information about specifying the encoding of a python source file.

Once you specify the encoding of the source file, you shouldn't have to decode the text.

vfilby
+2  A: 

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

Alex Martelli
hi alex ,look the updated2
zjm1126
@zjm1126,make `a = u'xxx'`
SpawnCxy
but the 'a' is google-app-engine give me ,i can't change it
zjm1126
well,then `print a.decode('utf-8').encode('gb2312')`
SpawnCxy
thanks a lot...
zjm1126
+1  A: 

The following code works for me:

# coding: utf8
print u'哈哈'.encode('utf-8')

The #coding comment tells Python the encoding of the file itself, so you can embed UTF-8 characters in it directly. And if you start from a Unicode string, there is no need to decode it and the re-encode it.

Will McCutchen