1. 编码是什么? #

2. str 与 bytes #

类型 含义 典型场景
str 程序里的文本(Unicode 字符) 变量、JSON 字段、业务逻辑
bytes 编码后的二进制数据 读文件、网络传输、写磁盘
s = "Hello 世界"                    # str
b = s.encode("utf-8")              # bytes: b'Hello \xe4\xb8\x96\xe7\x95\x8c'
print(b.decode("utf-8"))           # 还原为 str: Hello 世界

3. UTF-8 #

text = "你好"
print(text.encode("utf-8"))   # b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(len("A".encode("utf-8")))   # 1
print(len("你".encode("utf-8")))  # 3

4. 读写文件 #

# 写入
with open("data.txt", "w", encoding="utf-8") as f:
    f.write("你好")

# 读取
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()

5. 项目开发要点 #