更新时间:2023-01-22 19:33:36
无需正则表达式即可:
>>>string = "特殊的 $#! 字符空格 888323">>>''.join(e for e in string if e.isalnum())'特殊字符空格888323'您可以使用 str.isalnum
:
S.isalnum() ->布尔值如果 S 中的所有字符都是字母数字,则返回 TrueS 中至少有一个字符,否则为 False.
如果您坚持使用正则表达式,其他解决方案也可以.但是请注意,如果可以在不使用正则表达式的情况下完成,那是***的方法.
I need to remove all special characters, punctuation and spaces from a string so that I only have letters and numbers.
This can be done without regex:
>>> string = "Special $#! characters spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'
You can use str.isalnum
:
S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
If you insist on using regex, other solutions will do fine. However note that if it can be done without using a regular expression, that's the best way to go about it.