Answers:
正则表达式可以解救!
import re
s = re.sub('[^0-9a-zA-Z]+', '*', s)
例:
>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'
re.sub("[\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+", " ", ":%# unicode ΣΘΙП@./\n")
import re; regex = re.compile('[^0-9a-zA-Z]+'); regex.sub('*', 'h^&ell.,|o w]{+orld')
\W是,对于非单词字符,它几乎是相同的,但是允许使用下划线作为单词字符(不知道为什么):docs.python.org/3.6/library/re.html#index-32
用途\W等同于[^a-zA-Z0-9_]。查看文档https://docs.python.org/2/library/re.html
Import re
s = 'h^&ell`.,|o w]{+orld'
replaced_string = re.sub(r'\W+', '*', s)
output: 'h*ell*o*w*orld'
更新:此解决方案还将排除下划线。如果只希望排除字母和数字,那么使用nneonneo解决方案更为合适。
\W仅等效[^a-zA-Z0-9_]于Python2.x。在Python 3.x中,仅当使用/ 标志时才\W+等效。[^a-zA-Z0-9_]re.ASCIIre.A