[Python] Why does ENcoding a string result in a DEcoding error (UnicodeDecodeError)?

Discussão em 'Python' iniciado por Stack, Junho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm really confused. I tried to encode but the error said can't decode....

    >>> "你好".encode("utf8")
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)


    I know how to avoid the error with "u" prefix on the string. I'm just wondering why the error is "can't decode" when encode was called. What is Python doing under the hood?


    See also: unicode().decode('utf-8', 'ignore') raising UnicodeEncodeError , the other way around.

    Continue reading...

Compartilhe esta Página