从python字符串中删除unicode字符

V.A*_*Anh 13 python unicode python-2.7

我在Python中有一个字符串,如下所示:

u'\u200cHealth & Fitness'
Run Code Online (Sandbox Code Playgroud)

我怎么能删除

\u200c
Run Code Online (Sandbox Code Playgroud)

部分来自字符串?

Aro*_*unt 38

您可以将其编码ascii并忽略错误:

u'\u200cHealth & Fitness'.encode('ascii', 'ignore')
Run Code Online (Sandbox Code Playgroud)

输出:

'Health & Fitness'
Run Code Online (Sandbox Code Playgroud)

  • 这显然适用于上面的示例,但您强制将字符串转换为 ascii,丢失了所有 unicode 字符,这显然不是一个适用于所有人的解决方案 (4认同)

Hay*_*yat 18

如果你有一个包含Unicode字符的字符串,比如

s = "Airports Council International \u2013 North America"
Run Code Online (Sandbox Code Playgroud)

然后你可以尝试:

newString = (s.encode('ascii', 'ignore')).decode("utf-8")
Run Code Online (Sandbox Code Playgroud)

输出将是:

Airports Council International North America

Upvote如果有帮助 :)


小智 13

我只是使用替换因为我不需要它:

varstring.replace('\u200c', '')
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下:

u'\u200cHealth & Fitness'.replace('\u200c', '')
Run Code Online (Sandbox Code Playgroud)

  • 这是通用解决方案,因为 ascii 也可能删除一些其他 Unicode 字符。 (4认同)
  • 这实际上比大多数字符串中接受的答案要好。\u200c 是一个零宽度的非连接符,它是一个不寻常的空白类型字符,被 `strip()` 忽略。在大多数情况下,对于 unicode strs,您不想“编码(ascii,忽略)”。 (3认同)

Dia*_*ana 5

对我来说以下有效

mystring.encode('ascii', 'ignore').decode('unicode_escape')
Run Code Online (Sandbox Code Playgroud)

  • 您可以通过解释为什么这段代码有效以及您在这里做什么来改进您的答案。这样,其他人就可以受到教育。 (2认同)