|
|
这两个方法是 Python 中字符串(str)和字节串(bytes)之间转换的核心方法。
encode() - 字符串 → 字节串
将字符串按照指定编码转换为字节串。 - # 语法
- str.encode(encoding='utf-8', errors='strict')
复制代码 示例:
- text = "Python编程"
- # 默认 UTF-8 编码
- bytes_data = text.encode()
- print(bytes_data) # b'Python\xe7\xbc\x96\xe7\xa8\x8b'
- # GBK 编码
- bytes_gbk = text.encode('gbk')
- print(bytes_gbk) # b'Python\xb1\xe0\xb3\xcc'
- # 处理错误
- text.encode('ascii', errors='ignore') # 忽略无法编码的字符
- text.encode('ascii', errors='replace') # 用 ? 替换
复制代码
|
|