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

2024-04-25 14:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

尝试:

s = filter(str.isalnum, s)

在Python3中:

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

编辑: 意识到OP想用“*”替换非字符。我的回答不合适

雷鬼去救我!

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'

Python的方式。

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

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

"h^&i => "h**i与regex解决方案中的不同。

相关问题 更多 >