print vs sys.stdout.write, and UnicodeError

B

Brent Lievers

Greetings,

I have observed the following (python 2.5.1):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in
position 0: ordinal not in range(128)

Is this correct? My understanding is that print ultimately calls
sys.stdout.write anyway, so I'm confused as to why the Unicode error
occurs in the second case. Can someone explain?

Thanks,

Brent
 
M

Martin Marcher

25 Oct 2007 17:37:01 GMT said:
Greetings,

I have observed the following (python 2.5.1):

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in
position 0: ordinal not in range(128)
é

Is this correct? My understanding is that print ultimately calls
sys.stdout.write anyway, so I'm confused as to why the Unicode error
occurs in the second case. Can someone explain?

you forgot to encode what you are going to "print" :)
 
B

Brent Lievers

Martin Marcher said:
you forgot to encode what you are going to "print" :)

Thanks. I obviously have a lot to learn about both Python and Unicode ;-)

So does print do this encoding step based on the value of
sys.stdout.encoding? In other words, something like:

sys.stdout.write(textstr.encode(sys.stdout.encoding))

I'm just trying to understand why encode() is needed in the one case but
not the other.

Cheers,

Brent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top