python3中utf-8编码如何转换?

Python3中UTF-8编码转换需用encode()将字符串转为字节,decode()将字节转为字符串,文件读写时应指定encoding='utf-8'以避免编码问题。

在 Python3 中,UTF-8 编码的转换主要涉及字符串(str)和字节(bytes)之间的相互转换。Python3 默认使用 Unicode 处理字符串,而 UTF-8 是一种常见的编码方式,用于将 Unicode 字符串转换为字节序列。

字符串转为 UTF-8 字节

使用字符串的 encode() 方法可以将 str 类型转换为 UTF-8 编码的 bytes 类型。

  • text = "你好,世界"
  • utf8_bytes = text.encode('utf-8')
  • print(utf8_bytes) # 输出: b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'

UTF-8 字节转为字符串

使用 bytes 的 decode() 方法可将 UTF-8 编码的字节恢复为原始字符串。

  • utf8_bytes = b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
  • text = utf8_bytes.decode('utf-8')
  • print(text) # 输出: 你好,世界

处理文件读写时的 UTF-8 编码

在读写文本文件时,建议显式指定 encoding 参数为 'utf-8',避免因系统默认编码不同导致问题。

  • # 写入 UTF-8 文件
  • with open('data.txt', 'w', encoding='utf-8') as f:
  •   f.write("包含中文的内容")
  • # 读取 UTF-8 文件
  • with open('data.txt', 'r', encoding='utf-8') as f:
  •   text = f.read()
  •   print(text)

基本上就这些。只要记住 encode 转字节、decode 转字符串,文件操作加 encoding='utf-8',就能避免大多数编码问题。