Python str.encode() 方法
描述
把字符串编码为字节串(bytes)。对应的 bytes.decode() 把字节串解码回字符串。
语法
str.encode(encoding='utf-8', errors='strict')
参数
| 参数 | 说明 |
|---|---|
encoding | 编码 |
errors | 错误处理方式 |
返回值
bytes
实例
b = "你好".encode("utf-8")
print(b, len(b))
print(b.decode("utf-8"))
print("你好".encode("gbk"))以上实例输出结果为:
b'\xe4\xbd\xa0\xe5\xa5\xbd' 6
你好
b'\xc4\xe3\xba\xc3'