Python decoding Unicode is not supported

PythonEncodingUtf 8Character Encoding

Python Problem Overview


I am having a problem with my encoding in Python. I have tried different methods but I can't seem to find the best way to encode my output to UTF-8.

This is what I am trying to do:

result = unicode(google.searchGoogle(param), "utf-8").encode("utf-8")

searchGoogle returns the first Google result for param.

This is the error I get:

exceptions.TypeError: decoding Unicode is not supported

Does anyone know how I can make Python encode my output in UTF-8 to avoid this error?

Python Solutions


Solution 1 - Python

Looks like google.searchGoogle(param) already returns unicode:

>>> unicode(u'foo', 'utf-8')

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    unicode(u'foo', 'utf-8')
TypeError: decoding Unicode is not supported

So what you want is:

result = google.searchGoogle(param).encode("utf-8")

As a side note, your code expects it to return a utf-8 encoded string so what was the point in decoding it (using unicode()) and encoding back (using .encode()) using the same encoding?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsimonbsView Question on Stackoverflow
Solution 1 - PythonyakView Answer on Stackoverflow