Is there a way to change the default string encoding?

R

Ron Garret

Is there a way to change the default string encoding used by the
string.encode() method? My default environment is utf-8 but I need it
to be latin-1 to avoid errors like this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 4:
ordinal not in range(128)

I can't change the code to pass an encoding argument to the decode
method because it's someone else's code.

Thanks,
rg
 
P

Peter Otten

Ron said:
Is there a way to change the default string encoding used by the
string.encode() method?

encode() or decode()? Encoding is best handled by the output stream, e. g.
passing codecs.open(...) instead of the builtin open(...).

My default environment is utf-8 but I need it
to be latin-1 to avoid errors like this:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 4:
ordinal not in range(128)

If your environment were latin-1, you'd get the same error because Python
assumes ascii by default.
I can't change the code to pass an encoding argument to the decode
method because it's someone else's code.

Does that code accept unicode strings? Try to pass u"Andre\xe9 Ramel"
instead of the byte string.

If all else fails there's
u'Andre\xe9 Ramel'

but that's an evil hack, you should rather talk to the maintainer of the
offending code to update it to accept unicode.

Peter
 
R

Ron Garret

Peter Otten said:
If all else fails there's

u'Andre\xe9 Ramel'

but that's an evil hack, you should rather talk to the maintainer of the
offending code to update it to accept unicode.

Yes, but I need to hack around it until I can get it fixed.

Thanks!

rg
 
P

Peter Otten

Ron said:
Yes, but I need to hack around it until I can get it fixed.

Oops, the snippet above omits the actual hack. It should be
u'Andre\xe9 Ramel'

Peter
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top