Skip to main content
 首页 » 编程设计

python之删除字符串 Python 中的 Unicode 代码 (\uxxx)

2024年10月01日24xiaohuochai

我在文档中有一些 Unicode 字符串。我只想删除此 Unicode 代码或用一些空格 ("") 替换它。示例 =“”

doc = "Hello my name is Ruth \u2026! I really like swimming and dancing \ud83c" 

如何将其转换为以下内容?

doc = "Hello my name is Ruth! I really like swimming and dancing" 

我已经试过了:https://stackoverflow.com/a/20078869/5505608 ,但没有任何反应。我正在使用 Python 3。

请您参考如下方法:

您可以编码为 ASCII 并忽略错误(即无法转换为 ASCII 字符的代码点)。

>>> doc = "Hello my name is Ruth \u2026! I really like swimming and dancing \ud83c" 
>>> doc.encode('ascii', errors='ignore') 
b'Hello my name is Ruth ! I really like swimming and dancing ' 

如果尾随空格让您感到困扰,请去掉它。根据您的用例,您可以使用 ASCII 再次解码结果。链接一切看起来像这样:

>>> doc.encode('ascii', errors='ignore').strip().decode('ascii') 
'Hello my name is Ruth ! I really like swimming and dancing'