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


Answers:


182

正则表达式可以解救!

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'

7
如果您经常处理unicode,则可能还需要保留所有非ASCII unicode符号:re.sub("[\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+", " ", ":%# unicode ΣΘΙП@./\n")
zhazha

如果要在字符串中保留空格,只需在方括号内添加空格:s = re.sub('[^ 0-9a-zA-Z] +','*',s)
stackPusher

2
如果进行了多次替换,则如果您预编译了正则表达式,则执行起来会更快一些,例如import re; regex = re.compile('[^0-9a-zA-Z]+'); regex.sub('*', 'h^&ell.,|o w]{+orld')
Chris

还要注意的\W是,对于非单词字符,它几乎是相同的,但是允许使用下划线作为单词字符(不知道为什么):docs.python.org/3.6/library/re.html#index-32
JHS

36

pythonic方式。

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

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

"h^&i => "h**i不像"h*i"正则表达式解决方案那样。


11

尝试:

s = filter(str.isalnum, s)

在Python3中:

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

编辑:意识到OP希望用'*'替换非字符。我的答案不合适


11

用途\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解决方案更为合适。


1
请注意,这\W仅等效[^a-zA-Z0-9_]于Python2.x。在Python 3.x中,仅当使用/ 标志时才\W+等效。[^a-zA-Z0-9_]re.ASCIIre.A
WiktorStribiżew19年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.