unicode string problems

Martin v. Loewis martin at v.loewis.de
Mon Apr 1 18:24:52 EST 2002


Gonçalo Rodrigues <op73418 at mail.telepac.pt> writes:

> My problem is the following:
> 
> Let f be a file object. If I do
> 
> f.write("Março 2002")
> 
> all goes well. But if I try

It depends on your meaning of "well". It writes 9 bytes into the file,
yes.

> f.write("Março 2002" + march.Name())
> 
> where march.Name() returns a unicode string I get a unicode error. I
> tried converting both unicodes to strings via str but obviously I got an
> error (in the first string the culprit is the "ç" character).
> 
> Can someone help me out here and show me the way to write these strings
> to the file?

If you want to write text into a file, you should know what encoding
you want to use in this file. Then make sure that all byte strings
written to the file indeed use that encoding.

In the specific case,

f.write("Março 2002" + march.Name().encode("iso-8859-1"))

will do the right thing, assuming you want the text to be encoded in
that encoding.

HTH,
Martin




More information about the Python-list mailing list