python 错误 UnicodeEncodeError: 'charmap' codec can't encode characters :character maps to undefined
当我们使用不正确的编解码器将字符串编码为字节时,会出现 Python “UnicodeEncodeError: 'charmap' codec can't encode characters in position”。 要解决该错误,需要在打开文件或对字符串进行编码时指定正确的编码,例如 UTF-8
。
下面是产生错误的示例代码
my_str = 'hello 𝘈Ḇ𝖢𝕯٤ḞԍНǏ'
# ⛔️ UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-8: character maps to <undefined>
my_bytes = my_str.encode('cp856')
该错误是因为字符串无法使用指定的编码进行编码。
要解决错误,需要使用正确的编码对字符串进行编码,例如 UTF-8
。
my_str = 'hello 𝘈Ḇ𝖢𝕯٤ḞԍНǏ'
my_bytes = my_str.encode('utf-8')
# 👇️ b'hello \xf0\x9d\x98\x88\xe1\xb8\x86\xf0\x9d\x96\xa2\xf0\x9d\x95\xaf\xd9\xa4\xe1\xb8\x9e\xd4\x8d\xd0\x9d\xc7\x8f'
print(my_bytes)
utf-8 编码能够以 Unicode 编码超过一百万个有效字符代码点。
我们可以在官方文档的这个表格中查看所有标准编码。
如果在打开文件时遇到错误,需要在调用 open()
函数时将 encoding
关键字参数设置为 utf-8。
my_str = 'hello 𝘈Ḇ𝖢𝕯٤ḞԍНǏ'
with open('example.txt', 'w', encoding='utf-8') as f:
f.write(my_str)
下面是完整的代码
my_str = 'hello 𝘈Ḇ𝖢𝕯٤ḞԍНǏ'
# 👇️ 字符串编码为字节
my_bytes = my_str.encode('utf-8')
print(my_bytes)
# 👇️ 字节解码为字符串
my_str_again = my_bytes.decode('utf-8')
print(my_str_again) # 👉️ "hello 𝘈Ḇ𝖢𝕯٤ḞԍНǏ"
解码字节对象时,我们必须使用与将字符串编码为字节对象相同的编码。
如果使用 utf-8 编码时错误仍然存在,需要尝试将 errors
关键字参数设置为 ignore 以忽略无法编码的字符。
my_str = 'hello 𝘈Ḇ𝖢𝕯٤ḞԍНǏ'
# 👇️ 字符串编码为字节
my_bytes = my_str.encode('utf-8', errors='ignore')
print(my_bytes)
# 👇️ 字节解码为字符串
my_str_again = my_bytes.decode('utf-8', errors='ignore')
print(my_str_again) # 👉️ "hello 𝘈Ḇ𝖢𝕯٤ḞԍНǏ"
请注意,忽略无法编码的字符可能会导致数据丢失。
我们还可以将 errors 关键字参数设置为 ignore 以在打开文件时忽略任何编码错误。
my_str = 'hello 𝘈Ḇ𝖢𝕯٤ḞԍНǏ'
with open('example.txt', 'w', encoding='utf-8', errors='ignore') as f:
f.write(my_str)
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串