When you define Chinese in a code file, you often experience problems, either coding incorrectly or not printing properly.
For example, dict_chinese.py:
#!/usr/bin/python
a={' name ': ' Fengshou '}
b={' name ': "Bumper"}
print "A=", a
print "b=", b
Question 1
execution, viewing results
$ python dict_chinese.py
File "dict_chinese.py", line 5
syntaxerror:non-ascii character ' \xe4 ' in File Dict_chin ese.py on line 5, but no encoding declared; Http://www.python.org/peps/pep-0263.html for details
reason
This is a problem with Python encoding, the default encoding format in Python is in ASCII format, so the default is to incorrectly encode Chinese characters. Solutions
Defines the encoding format.
In each subsequent Python file that needs to display Chinese characters, the encoding format is first defined, and the position requirement must be in the first or second row, if the first row is #!/usr/bin/python, then in the second row, the other is defined in the first line.
Take UTF-8 encoding as an example.
The code is modified to:
#!/usr/bin/python
#-*-coding:utf-8-*-
a={' name ': ' Fengshou '}
b={' name ': ' Harvest '}
print ' a= ', a
Print "b=", b
Question 2
Execute, view output:
$ python dict_chinese.py
a= {' name ': ' Fengshou '}
b= {' name ': ' \xe4\xb8\xb0\xe6\x94\xb6 '}
You can see that Chinese content is still not displayed correctly. Solutions
Format conversion using JSON, and then print out the output.
The code is modified to:
#!/usr/bin/python
#-*-coding:utf-8-*-
a={' name ': ' Fengshou '}
b={' name ': ' Harvest '}
print ' a= ', a
print "b=", b
import json result
= Json.dumps (b, encoding= ' UTF-8 ', ensure_ascii=false)
print "b=" , result
$ python dict_chinese.py
a= {' name ': ' Fengshou '}
b= {' name ': ' \xe4\xb8\xb0\xe6\x94\xb6 '}
b= {' name ': ' Bumper Harvest "}
Finally, I can view the Chinese language normally. Reference
https://segmentfault.com/a/1190000002447836
http://blog.csdn.net/ksearch/article/details/35241019