Somethings about the coding in Python

来源:互联网 发布:java try的用法 编辑:程序博客网 时间:2024/05/16 12:04

In python3,the words will be coded in Unicode,so python3 support many languages.
- ord():output the int number of a charactor:

ord('a')ord('中')
  • chr():output the charactor of a specific codeing number:
#the charactor 'B'chr(66)##the charactor '文'chr(25991)
  • the type of str is coded with Unicode,the type of bytes is coded with ASCII,which means every charactor only costs 1 byte
  • you can use encode() to change the coding:
#Unicode to ASCII'ABC'.encode('ascii')#Unicode to UTF-8'我爱你'.encode('utf-8')
  • the data I received from network/disk is bytes(ASCII/UTF-8),So if I want to change it to Unicode,I can use decode function:
b'ABC'.decode('ascii')b'\xe4\xb8'.decode('utf-8')
  • we will often meet the coding change between Unicode and bytes(UTF-8/ASCII).So usually we encouraged to use the UTF-8 all the time.So when the Python interpreter read the file,we need make it follow the UFT-8.You are supposed to add this two lines in the top of the file:
#!/usr/bin/python3# -*- coding:utf-8 -*-

The first line is the path of the python.It tells the Linux that this file is a python procedure .
The second line is to tell the python interpreter that this file should be read in UTF-8 in the memory.