By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,095 Members | 1,586 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,095 IT Pros & Developers. It's quick & easy.

Unicode string formating

P: n/a
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
Nov 30 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
nico schrieb:
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
Nov 30 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.