name = caffé
print name
Python gave me an error on print: ascii' codec can't encode character u'\xe9' in position 5: ordinal not in range(128)

I have put # -*- coding: utf-8 -*- on the top of the script
what else should I look into? thanks.

name = caffé
print name
Python gave me an error on print: ascii' codec can't encode character u'\xe9' in position 5: ordinal not in range(128)

I have put # -*- coding: utf-8 -*- on the top of the script

If you remove that line from the top of your script does it change the result?

Also, have you tried utf-16 ?

If you remove that line from the top of your script does it change the result?
No, still the same error

Also, have you tried utf-16 ?

same error

Perhaps you should check this link http://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/ and change the environment variable LC_CTYPE (you should also check if you can change it in your program, using os.environ ). I can't test your problem here, because I'm having a french configuration, so the é prints well. By the way, if this is french, there is only one f in "café".

name = caffé
print name

Don't you mean :
name="caffé"

This works on my Windows machine ...

# -*- coding: iso-8859-15 -*-
# check encoding in http://www.python.org/dev/peps/pep-0263/
# print strings with unicode characters

name = 'café'
print(name)

"""
my output -->
café
"""

Using Python30 ...

# printing unicode characters
# if don't have a french keyboard use this
# é --> \xE9 hex from any ascii table
print('caf' + '\xE9')
# or simply
print('caf\xE9')

"""
my output -->
café
café
"""

I think this will work with Python25.

Here is the solution:
if name:
try:
name = str(name)
except UnicodeEncodeError:
name = str(name.encode('utf-8'))
print name

Perhaps you should check this link http://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/ and change the environment variable LC_CTYPE (you should also check if you can change it in your program, using os.environ ). I can't test your problem here, because I'm having a french configuration, so the é prints well. By the way, if this is french, there is only one f in "café".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.