UnicodeEncodeError - a bit out of my element...

liupeng liupeng at 18mail.cn
Wed Apr 11 11:35:47 EDT 2007


I cut from Sam Python Phrasebook
"Converting Unicode to Local Strings"

import string locStr = "El " 
uniStr = u"Ni\u00F1o" 
print uniStr.encode('utf-8') 
print uniStr.encode('utf-16') 
print uniStr.encode('iso-8859-1') 
#Combine local and unicode results 
#in new unicode string 
newStr = locStr+uniStr 
print newStr.encode('iso-8859-1') 
#ascii will error because character '\xF1' 
#is out of range 
asciiStr = newStr.encode('iso-8859-1') 
asciiStr =asciiStr.translate(\ 
    string.maketrans('\xF1','n'), '') 
print asciiStr.encode('ascii') 
print newStr.encode('ascii')

unicode_str.py 

Niño 
ÿN|I|ñ|o 
Niño 
El Niño 
El Nino 
Traceback (most recent call last): 
  File "C:\books\python\CH2\code\unicode_str.py", 
line 19, in ? 
    print newStr.encode('ascii') 
UnicodeEncodeError: 'ascii' codec can't encode 
 character u'\xf1' in position 5: ordinal not in 
 range(128)

On Wed, Apr 11, 2007 at 08:16:07AM -0700, erikcw wrote:
> Hi all,
> 
> I'm trying to parse an email message, but am running into this
> exception.
> 
> Traceback (most recent call last):
>   File "wa.py", line 336, in ?
>     main()
>   File "wa.py", line 332, in main
>     print out['msg']
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in
> position 238: ordinal not in range(128)
> 
> How can I decode/encode this string to print to stdout and send again
> in another email?  Do I have to know what language the email is in?
> 
> Thanks!
> Erik
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20070411/f55ef178/attachment.sig>


More information about the Python-list mailing list