Python FAQ: syntaxerror: Non-ASCII character Python

Source: Internet
Author: User
Tags windows ssh client
Chinese problems in Python have always been a headache for beginners. Article I will explain this knowledge in detail. Of course, it is almost certain that in future versions, python will completely solve this problem, so we don't have to worry about it.

Let's take a look at the Python version:

>>> Import Sys
>>> SYS. Version
' 2.5.1 (r0000: 54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] '

(1) create a file chinesetest. py in Notepad. The default value is ANSI:

S = " Chinese "
Print S

Test it:

E: \ project \ Python \ test> Python chinesetest. py

File "chinesetest. py", line 1
Syntaxerror: Non-ASCII character '\ xd6' in file chinesetest. py on line 1, but noencodingdeclared; see http://www.pytho
N.org/peps/pep-0263.html for details

Secretly changed the file encoding into UTF-8:

E: \ project \ Python \ test> Python chinesetest. py
File "chinesetest. py", line 1
Syntaxerror: Non-ASCII character '\ xe4' in file chinesetest. py on line 1, but noencodingdeclared; see http://www.pytho
N.org/peps/pep-0263.html for details

No help...
Now that it provides a URL, let's take a look. After a brief look, we finally know that if the file contains non-ASCII characters, We need to specify the encoding declaration in the first or second line. Change the encoding of the chinesetest. py file to ANSI and add the encoding statement:

# Coding = GBK
S = " Chinese "
Print S

Try again:

E: \ project \ Python \ test> Python chinesetest. py
Chinese

Normal :)

(2) Take A Look At its length:

# Coding = GBK
S = " Chinese "
Print Len (s)

Result: 4.
S is 'str' type. Therefore, a Chinese character is equivalent to two English characters, so the length is 4.
We write as follows:

# Coding = GBK
S = " Chinese "
S1 = u " Chinese "
S2 = Unicode (S, " GBK " ) # If any parameter is omitted, the default ASCII value of python is used for decoding.
S3 = S. Decode ( " GBK " ) # Converting STR to Unicode is decode, and Unicode functions are used in the same way.
Print Len (S1)
Print Len (S2)
Print Len (S3)

Result:
2
2
2
(3) Next let's take a look at the file processing: create a file named test.txt. The file format is ANSI, the content is ABC Chinese, and it is read using python.

# Coding = GBK
Print Open ( " Test.txt " ). Read ()

Result: ABC (Chinese)
The file format into UTF-8:
Result: ABC Juan
Obviously, decoding is required here:

# Coding = GBK
Import Codecs
Print Open ( " Test.txt " ). Read (). Decode ( " UTF-8 " )

Result: ABC (Chinese)
I used editplus to edit test.txt, but when I used the notepad that came with windows to edit and coexist in UTF-8 format,
Running error:

# Coding = GBK
Import codecs
Print open ("test.txt"). Read (). Decode ("UTF-8 ")

Originally, some software, such as Notepad, will insert three invisible characters (0xef 0xbb 0xbf, BOM) at the beginning of the file when saving a file encoded in UTF-8 ).
Therefore, we need to remove these characters during reading. The codecs module in Python defines this constant:

# Coding = GBK
Import Codecs
Print Open ( " Test.txt " ). Read (). Decode ( " UTF-8 " )

Result: ABC (Chinese)

(4) A few issues left behind
In the second part, we use the Unicode function and decode method to convert STR to Unicode. Why do the parameters of these two functions use "GBK?
The first response is that GBK (# Coding = GBK) is used in our encoding statement, but is it true?
Modify the source file:

# Coding = UTF-8
S = " Chinese "
Print Unicode (S, " UTF-8 " )

Run, error:

Traceback (most recent call last ):
File "chinesetest. py", line 3, in < Module >
S = Unicode (S, "UTF-8 ")
Unicodedecodeerror: 'utf8' codec can't decode bytes in position 0-1: Invalid Data

Obviously, if both sides use GBK, I keep the same UTF-8 on both sides, and it should be normal, so as not to report an error.
For a further example, if the conversion here still uses GBK:

# Coding = UTF-8
S = " Chinese "
Print Unicode (S, " GBK " )

Result: Chinese
I read an English document to explain the principle of print in Python:
When Python executes a print statement, it simply passes the output to the Operating System (using fwrite () or something like it ), and some other program is responsible for actually displaying that output on the screen. for example, on Windows, it might be the Windows console subsystem that displays the result. or if you're using Windows and running python on a Unix box somewhere else, your windows SSH client is actually responsible for displaying the data. if you are running python in an xterm on UNIX, then xterm and your X Server handle the display.

To print data reliably, you must knowEncodingThat this display program expects.

To put it simply, print in Python directly transmits the string to the operating system, so you need to decode STR to the same format as the operating system. Cp936 (almost the same as GBK) is used in windows, so GBK can be used here.
Last test:

# Coding = UTF-8
S = " Chinese "
Print Unicode (S, " Cp936 " )

Result: Chinese

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.