Handle wrongly encoded character in Python unicode string

前端 未结 5 595
暗喜
暗喜 2020-12-06 10:01

I am dealing with unicode strings returned by the python-lastfm library.

I assume somewhere on the way, the library gets the encoding wrong and returns a unicode str

5条回答
  •  日久生厌
    2020-12-06 10:39

    At the beginning of your code, just after imports, add these 3 lines.

    import sys  # import sys package, if not already imported
    reload(sys)
    sys.setdefaultencoding('utf-8')
    

    It will override system default encoding (ascii) for the course of your program.

    Edit: You shouldn't do this unless you are sure of the consequences, see comment below. This post is also helpful: Dangers of sys.setdefaultencoding('utf-8')

提交回复
热议问题