替换字符串中的所有非字母数字字符

我有一个字符串,我想用它来替换任何不是标准字符或数字的字符,比如(a-z 或0-9)加星号。比如“ h ^ & ell”。,| o w ]{ + orld”被替换为“ h * ell * o * w * orld”。请注意,“ ^ &”等多个字符将被替换为一个星号。我该怎么做呢?

156510 次浏览

正则表达式拯救!

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'

蟒蛇的方式。

print "".join([ c if c.isalnum() else "*" for c in s ])

但是,这并不涉及对多个连续的不匹配字符进行分组,即。

"h^&i => "h**i不是正则表达式解决方案中的 "h*i"

试试:

s = filter(str.isalnum, s)

在 Python 3中:

s = ''.join(filter(str.isalnum, s))

编辑: 意识到 OP 想用“ *”替换非字符

使用相当于 [^a-zA-Z0-9_]\W。检查文档 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'

Update: 此解决方案也将排除下划线。如果您希望只排除字母和数字,那么使用 nnicneo 的解决方案更为合适。