我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。


当前回答

这可以不使用regex完成:

>>> string = "Special $#! characters   spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'

你可以使用str.isalnum:

S.isalnum() -> bool 如果S中的所有字符都是字母数字,则返回True 且S中至少有一个字符,否则为假。

如果坚持使用正则表达式,其他解决方案也可以。但是请注意,如果可以在不使用正则表达式的情况下完成,那么这是最好的方法。

其他回答

s = re.sub(r"[-()\"#/@;:<>{}`+=~|.!?,]", "", s)
#!/usr/bin/python
import re

strs = "how much for the maple syrup? $20.99? That's ricidulous!!!"
print strs
nstr = re.sub(r'[?|$|.|!]',r'',strs)
print nstr
nestr = re.sub(r'[^a-zA-Z0-9 ]',r'',nstr)
print nestr

你可以添加更多的特殊字符,这将被“意味着什么,即他们将被删除”所取代。

import re
my_string = """Strings are amongst the most popular data types in Python. We can create the strings by enclosing characters in quotes. Python treats single quotes the 

和双引号一样。”""

# if we need to count the word python that ends with or without ',' or '.' at end

count = 0
for i in text:
    if i.endswith("."):
        text[count] = re.sub("^([a-z]+)(.)?$", r"\1", i)
    count += 1
print("The count of Python : ", text.count("python"))

字符串。标点符号包含以下字符:

'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'

可以使用translate和maketrans函数将标点符号映射为空值(替换)

import string

'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))

输出:

'This is A test'

较短的方法:

import re
cleanString = re.sub('\W+','', string )

如果你想在单词和数字之间有空格,用''代替''