摆脱字符串变量中的无效 unicode 字符

Get rid of invalid unicode character in string variable

我输入了 python3 请求获取命令(不确定这是否是好的措辞),将其转换为 json,并解析它以接收名称:

'Harrison Elementary School \U0001f3eb'

我查了一下,unicode字符代表一个学校,Unicode School Character。但是当我打印它时,我得到:

return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f3eb' in position 27: character maps to <undefined>

我真的不在乎拥有那个 unicode 字符。这对我的目的并不重要。

如何从这个或我遇到的任何字符串中删除该 unicode 字符和任何其他 无效 字符?

这个字符并不是真的无效,只是undefined,所以你在编码的时候经常可以告诉编码器如何处理错误:

import codecs 

school_name = "Harrison Elementary School \U0001f3eb"
encoded_name = codecs.charmap_encode(school_name, 'ignore')
print(encoded_name) 

结果(b'Harrison Elementary School ', 28)

首先,您必须确定字符无效的原因。错误消息似乎是在您尝试打印字符串时生成的,这意味着无法使用默认输出编码对 Unicode 字符进行编码。对于 print,这应该是 sys.stdout.encoding

您可以自己对字符串进行编码并忽略无效的字符,但这会给您留下一个字节字符串。有必要 decode 将这些字节重新转换为 Unicode 字符串。

def sanitize(s, encoding, errors='ignore'):
    return s.encode(encoding, errors=errors).decode(encoding)

>>> import sys
>>> print(sanitize('Harrison Elementary School \U0001f3eb', sys.stdout.encoding))
Harrison Elementary School