删除字符串中的特殊字符(在列表中)

时间:2022-01-30 20:24:55

I have a bunch of special characters which are in a list like:

我有一堆特殊字符,如下所示:

special=[r'''\\''', r'''+''', r'''-''', r'''&''', r'''|''', r'''!''', r'''(''', r''')''', r'''{''', r'''}''',\
     r'''[''', r''']''', r'''^''', r'''~''', r'''*''', r'''?''', r''':''', r'''"''', r''';''', r''' ''']

And I have a string:

我有一个字符串:

stringer="Müller my [ string ! is cool^&"

How do I make this replacement? I am expecting:

我如何更换?我期待:

stringer = "Müller my string is cool"

Also, is there some builtin to replace these ‘special’ chars in Python?

另外,是否有一些内置用于替换Python中的这些“特殊”字符?

2 个解决方案

#1


1  

This can be solved with a simple generator expression:

这可以通过简单的生成器表达式来解决:

>>> ''.join(ch for ch in stringer if ch not in special)
'M\xc3\xbcllermystringiscool'

Note that this also removes the spaces, since they're in your special list (the last element). If you don't want them removed, either don't include the space in special or do modify the if check accordingly.

请注意,这也会删除空格,因为它们位于您的特殊列表中(最后一个元素)。如果您不希望删除它们,请不要包含特殊空格,或者相应地修改if检查。

#2


0  

If you remove the space from your specials you can do it using re.sub() but note that first you need to escape the special regex characters.

如果从特殊区域中删除空格,可以使用re.sub()执行此操作,但请注意,首先需要转义特殊的正则表达式字符。

In [58]: special=[r'''\\''', r'''+''', r'''-''', r'''&''', r'''|''', r'''!''', r'''(''', r''')''', r'''{''', r'''}''',\
     r'''[''', r''']''', r'''^''', r'''~''', r'''*''', r'''?''', r''':''', r'''"''', r''';''']

In [59]: print re.sub(r"[{}]".format(re.escape(''.join(special))), '', stringer, re.U)
Müller my  string  is cool

#1


1  

This can be solved with a simple generator expression:

这可以通过简单的生成器表达式来解决:

>>> ''.join(ch for ch in stringer if ch not in special)
'M\xc3\xbcllermystringiscool'

Note that this also removes the spaces, since they're in your special list (the last element). If you don't want them removed, either don't include the space in special or do modify the if check accordingly.

请注意,这也会删除空格,因为它们位于您的特殊列表中(最后一个元素)。如果您不希望删除它们,请不要包含特殊空格,或者相应地修改if检查。

#2


0  

If you remove the space from your specials you can do it using re.sub() but note that first you need to escape the special regex characters.

如果从特殊区域中删除空格,可以使用re.sub()执行此操作,但请注意,首先需要转义特殊的正则表达式字符。

In [58]: special=[r'''\\''', r'''+''', r'''-''', r'''&''', r'''|''', r'''!''', r'''(''', r''')''', r'''{''', r'''}''',\
     r'''[''', r''']''', r'''^''', r'''~''', r'''*''', r'''?''', r''':''', r'''"''', r''';''']

In [59]: print re.sub(r"[{}]".format(re.escape(''.join(special))), '', stringer, re.U)
Müller my  string  is cool