Home » Odeon Blogs » Liviu, Agile Bear »

Str to Ascii Conversion

Str to Ascii Conversion

After attending some python tests I stumbled upon a different DecodeError. The situation is simple: instantiate a string with special characters and try to decode it. Tring to use the Unicode to Ascii method failed.

  1. def test_title_unicode(self):
  2. from django.utils.encoding import force_unicode
  3. title = 'è something!'
  4. title = force_unicode(title)
  5. title = title.encode('ascii', 'xmlcharrefreplace')
  1. error

The difference between the Unicode to Ascii and the current iteration was revealed by printing the variable type:

  1. def test_title_unicode(self):
  2. from django.utils.encoding import force_unicode
  3. title = 'è something'
  4. print type(title)
  5. #title = force_unicode(title)
  6. #title = title.encode('ascii', 'xmlcharrefreplace')

In order to decode a str variable we use a different method:

  1. def test_title_unicode(self):
  2. title = 'è something'
  3. print title
  4. print type(title)
  5. title2 = title.decode('latin-1')
  6. print title2
  7. print type(title2)
  8. title3 = unicode(title2)
  9. print title3
  10. print type(title3)
  11. title = title3.encode('ascii', 'xmlcharrefreplace')
  12. print title

So make sure you check the type and choose the right aproach to convert.

PS: Remember that form.cleaned_data['var'] returns a unicode.



Leave a Comment :

(required)


(required)




(required)




(required)





Page generated in: 0.19s