Python - 如何从字符串中删除隐藏的符号?

rob*_*s85 6 python

有时候我有一个带有奇怪字符的字符串.它们在浏览器中不可见,但是是字符串的一部分,并以len()计算.我怎么能摆脱它?Strip()删除正常空间但不删除那些符号.

agf*_*agf 12

使用string模块中的字符类别.如果要允许所有可打印字符,则可以执行此操作

from string import printable
new_string = ''.join(char for char in the_string if char in printable)
Run Code Online (Sandbox Code Playgroud)

基于你的答案,你也可以这样做re.sub:

new_string = re.sub("[^{}]+".format(printable), "", the_string)
Run Code Online (Sandbox Code Playgroud)

此外,如果你想要查看字符串中的所有字符,即使是不可打印的字符,也可以随时查看

print repr(the_string)
Run Code Online (Sandbox Code Playgroud)

这将显示像\x00不可打印的字符.


Mih*_*lov 6

您可以使用str.isprintable()(来自PEP-3138)过滤字符串:

output_str = ''.join(c for c in input_str if c.isprintable())
Run Code Online (Sandbox Code Playgroud)


YOU*_*YOU 5

收集要启用的字符集并像这样删除其余字符

import re
text = re.sub("[^a-z0-9]+","", text, flags=re.IGNORECASE)
Run Code Online (Sandbox Code Playgroud)

它将删除除 a 到 z、A 到 Z 和 0 到 9 之外的任何字符。