'Ascii 'codec can't decode byte 0xef in position 0: ordinal not in range (128) -- Reference

Source: Internet
Author: User

Errors similar to ‘ascii’ codec ca n’t decode byte 0xef in position 0: ordinal not in range (128) often occur in Django view functions.

 

        Before solving the error, we must first understand the difference between unicode and utf-8.
        Unicode refers to the universal code, which is a kind of "code table". UTF-8 is the encoding method stored in this code table. Unicode does not have to be compiled into bytecode storage by utf-8, and other methods such as utf-16 and utf-7 can also be used. At present, most of them are turned into bytecode by utf-8.

 

        Secondly, the string types in Python are divided into two types: byte string and unicode string.
        If the encoding method is specified as utf-8 (# coding = utf-8) in the python file, then all strings with Chinese characters will be considered as utf-8 encoded byte strings (for example: mystr = "hello"), But the string generated in the function is considered a unicode string.
        The problem lies here. Unicode string and byte string cannot be mixed. Once mixed, this error will occur. E.g:
        self.response.out.write ("Hello" + self.request.get ("argu"))
        Among them, "Hello" is regarded as a byte string, and the return value of self.request.get ("argu") is regarded as a unicode string. Since the preset decoder is ascii, it cannot recognize the Chinese byte string. Then I got an error.

 

        There are two solutions:
        1. Convert all character strings to byte string.
            self.response.out.write ("Hello" + self.request.get ("argu"). encode ("utf-8"))
        2. Convert all strings into unicode strings.
            self.response.out.write (u "hello" + self.request.get ("argu"))
            Convert byte string to unicode string can be converted to unicode (unicodestring, "utf-8")

'ascii' codec can't decode byte 0xef in position 0: ordinal not in range (128)-quote

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.