The Python programming language is a relatively novel programming language. Compared with other languages, it has many different features that have aroused the interest of most developers. Here, we can analyze the related application methods of Python print to get a preliminary understanding of the application methods of this language.
Python print automatically encodes the output text, but does not write the file object. Therefore, when some strings are output normally using print, write to file is not necessarily the same as print. The encoding of print conversion is related to environment variables. Windows XP converts data to gbk. In linux, it is converted according to environment variables. Use the locale command in linux. For example, mine is:
- [zhaowei@papaya zhaowei]$ locale
- LANG=zh_CN
- LC_CTYPE="zh_CN"
- LC_NUMERIC="zh_CN"
- LC_TIME="zh_CN"
- LC_COLLATE="zh_CN"
- LC_MONETARY="zh_CN"
- LC_MESSAGES="zh_CN"
- LC_PAPER="zh_CN"
- LC_NAME="zh_CN"
- LC_ADDRESS="zh_CN"
- LC_TELEPHONE="zh_CN"
- LC_MEASUREMENT="zh_CN"
- LC_IDENTIFICATION="zh_CN"
- LC_ALL=
At this time, it will be considered gb2312. In python, you can use the locale module to obtain the encoding of the current environment:
- import locale
- print locale.getdefaultlocale()
Python print will automatically replace the string with this encoding during output. Let's take a look at the following. The word "Taobao" is a well-known word that is not found in gb2312. When you convert it to gb2312, an error will occur.
- #-*-Encoding: gb18030 -*-
- Import locale
- Import sys, encodings, encodings. aliases
- # Now a is unicode
- A = u'hangzhou'
- Print a. encode ("gb2312 ")
The above code reports an exception, which is the cause. But if it is print a directly, it can be output to assume that your environment variable is GBK, GB18030 or UTF-8 ). If your environment variable is GB2312, this print will report an error! So when processing text data from other places, it is best not to use GB2312 encoding, Chinese data, must use GB18030 or UTF-8!
Writing unicode data with the write of the file object will also lead to errors! Encoding conversion required
- #-*-Encoding: gb18030 -*-
- Import locale
- Import sys, encodings, encodings. aliases
- # Now a is unicode
- A = u'hangzhou'
- F = open ("aaa.txt", "w ")
- F. write ()
- F. close ()
The above is our introduction to Python print.