Unicode string formating

N

nico

Hi,
I need to do a lot of string formating, and I have strings and/or
unicode strings and when I do the following:
"%s %s" % (u'Salut', 'H\xe4llo'), I get an exception :
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position
1: ordinal not in range(128)

How can I insure I don't get an exception?
Thanks,
Nicolas
 
D

Diez B. Roggisch

nico said:
Hi,
I need to do a lot of string formating, and I have strings and/or
unicode strings and when I do the following:
"%s %s" % (u'Salut', 'H\xe4llo'), I get an exception :
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position
1: ordinal not in range(128)

How can I insure I don't get an exception?

By not mixing unicode and str together. Either you decode your str to
become unicode objects using the proper encoding - or you encode the
unicode-objects before:


string = "a string"

u_string = string.decode("ascii") # or whatever you need

print u"%s %s" % (u'Salut', u_string)

Or:

salut_string = u"Salut".encode("utf-8") # whatever encoding you need


print u"%s %s" % (salut_string, "foo")

Diez
 

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,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top