Chinese python coding (5)

python So far, a total of two versions, namely version 2.x and 3.x, 2020 according to official notice to stop python update and maintain, there are about 110 days from today, the junior partner is learning python It should be secretly glad that wave.

Learning python - secretly observed

 

python2.x version defaults ASCLL coding, python3.x version using the default UTF-8 encoding, both what difference does it make? The only difference is that if the code contains comments or Chinese, ASCLL coding garbled, UTF-8 but can display Chinese, that Chinese version python2.x display is not normal, python3.x normal version.

 

A. Why is garbled

Encoding and decoding correspondence, the corresponding data encoding, only with the corresponding data in the right way to decode, whereas the resulting data is wrong, garbled.

 

To a metaphor: the next Pharaoh set up a wifi password: abcdefgh, you want to use a password Pharaoh, Pharaoh tells you if you do not, you experiment 100 times Dounong not normal password (bar fine to say: I use wifi master key)

Drink plenty of water

 

II. How to solve the garbage

Solve the garbage is simple to find the right way decoding and encoding it. We continue to return to helloword project, the code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

# !usr/bin/env python

# -*- coding:utf-8 _*-

"""

@Author: Why grief

@Blog (personal blog address): shuopython.com

@WeChat Official Account (micro-channel public number): ape says python

@Github:www.github.com

@File:helloworld.py

@Time:2019/9/12 20:37

 

@Motto: short step a thousand miles, no small streams converge into a wonderful required the ocean, the program of life relentlessly accumulate!

"""

Print ( "Hello World" )

The first line tells the comment system, which is a Python executable, Linux / OS X system effective, Windows system ignores the annotation;

The second line is a comment in accordance with UTF-8 encoding to read the source code, although the default UTF-8 in pycharm, the line of code is optional, if the py file compile it into other environments? If other environment is not UTF-8, once the Chinese, inevitably garbled.

Other codes are useless comment code can be ignored!

 

III. Key summary

1. If the embodiment does not correspond to the encoding and decoding will be garbled

2. # - * - coding: utf-8 _ * - written in the beginning of the file, specify the default file encoding format utf-8

It is worth noting: In fact, coding can be considered a headache, later in the development you will inevitably encounter many codecs pit father accident, because the character encoding involves ascll, utf-8, unicode, gbk, gb18030 .........

Smile suddenly metamorphosis

 

you may also like:

1.pycharm / python / anaconda differences and connections

2.pycharm set header templates

 

Reproduced please specify : ape say Python »python Chinese encoding


Guess you like

Origin blog.51cto.com/14531342/2448446