删除不在Python中的集合中的字符

You*_*cha 1 python regex

我有一个字符串,我正在尝试删除所有不是字母数字的字符,也不在此集合中

'''!$%*()_-=+\/.,><:;'"?|'''.
Run Code Online (Sandbox Code Playgroud)

我知道这会删除所有非字母数字字符,但我怎样才能做得更好?

re.sub(r'\W+','',line)
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 7

Python 2.x非正则表达式解决方案:

punctuation = '''!$%*()_-=+\/.,><:;'"?|'''
allowed = string.digits + string.letters + punctuation
filter(allowed.__contains__, s)
Run Code Online (Sandbox Code Playgroud)

要过滤的字符串是s.(这可能不是长字符串的最快解决方案.)