第十三天:字符与编码

一、概述

1、类型

  • str 字符串
  • bytes 字节
  • bytearray 字节数组

2、字符编码架构

  • 字符集:赋值一个编码到某个字符,以便在内存中表示
  • 编码 Encoding:转化字符为原始字节形式
  • 解码 Decoding:一句编码名称转换原始字节到字符的过程

3、字符串存储

  • 编码只作用于文件存储或中间媒介转换
  • 内存中总是存储解码以后的文本

二、字符编码

1、ASCII

  • 存储在一个byte 0-127

2、latin-1

  • 存储在一个byte 128-255

3、UTF-8

  • 可变字节
    0-127 单字节
    128-2047 双字节
    2047 3-4字节
    每个字节使用范围是128-255

4、UTF-16

  • 2 byte存储字符, 2 byte用作标识

5、UTF-32

  • 4 byte存储字符

三、内置函数

  • 1、获取字符代码点 ord()
  • 2、获取代码点对应字符 chr()
ord('A') #查看字符代码点
chr(104) #查看代码点对应字符
65
'h'
  • 3、对特定字符编码 str.encode(‘编码’)
  • 4、将字节编码解码为字符文本 bytes.decode(‘编码’)
s1 = 'ABCD'
s1.encode('ASCII') #要指定使用哪种编码
s2 = '优品课堂'
s2.encode('UTF-8') #中文字符不能用ASCII编码
b'ABCD'
b'xe4xbcx98xe5x93x81xe8xafxbexe5xa0x82'
import sys
sys.getdefaultencoding() #获取当前默认编码
open('data.txt','w', encoding='utf8').write('天气')
open('data.txt', 'r',encoding = 'utf8').read()
'utf-8'
4
'天气'

四、类型转换

1、bytes

  • 手动声明 b‘ ’
  • 字符串编码 str.encode()
  • 构造函数 bytes()
b1 = b'xe4xbcx98xe5x93x81xe8xafxbexe5xa0x82'
type(b1)
bytes('abc', 'ascii')
bytes([87, 65, 89, 87])
bytes
b'abc'
b'WAYW'

2、bytesarray

  • 字符转换为字节数组 bytearray(‘字符’,‘编码’)
  • 将字节数组解码为字符 bytearray.decode()
s1 = 'abc'
s2 = '优品课堂'
ba = bytearray(s1, 'utf8')
type(ba)
ba[0] = 98 #改变字符
ba
bytearray(b'abc')
bytearray(b'bbc')

五、类型转换

  • BOM 处理
    • open(‘data.txt’, ‘w|r’, encoding=‘utf-8-sig’)
原文地址:https://www.cnblogs.com/linyk/p/11484420.html