Python UnicodeDecodeError when writing German letters

前端 未结 4 973
星月不相逢
星月不相逢 2020-12-17 21:53

I\'ve been banging my head on this error for some time now and I can\'t seem to find a solution anywhere on SO, even though there are similar questions.

Here\'s my c

4条回答
  •  攒了一身酷
    2020-12-17 22:34

    Why ascii if I say utf-8?

    Because in Python 2, "Bitte überprüfen" is not a Unicode string. Before it can be .encoded by your explicit call, Python must implicitly decode it to Unicode (This is also why it raises a UnicodeDecodeError), and it chooses ASCII because it has no other information to work with. The ü is represented with some byte with value >= 128, so it's not valid ASCII.

    The u prefix shown by @JuniorCompressor will make it a Unicode string, and you should specify the encoding for the file as well (don't just blindly set utf-8; it needs to match whatever your text editor saves the .py file with!).

    Switching to Python 3 is realistically (part of) a better long-term solution :) but it is still essential to understand the problem. See http://bit.ly/unipain for more details. The Python 2 behaviour is really a bug, or at least a failure to meet Pythonic design principles: Explicit is better than implicit, and here we see why very clearly ;)

提交回复
热议问题