import re
eliminate = re.compile('[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\s]+')
text = eliminate.sub("@", "你!好!")
text
# 输出:'你@好@'
text = eliminate.sub("", "你!好!")
text
# 输出:'你好'
如图所示:compile与sub组合替换掉已经匹配的字符串
本文通过Python的正则表达式模块re演示了如何使用compile与sub方法组合来替换字符串中包含的特殊字符,例如标点符号和空白字符。通过实例展示了将匹配到的字符替换为指定字符的过程。
import re
eliminate = re.compile('[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\s]+')
text = eliminate.sub("@", "你!好!")
text
# 输出:'你@好@'
text = eliminate.sub("", "你!好!")
text
# 输出:'你好'
如图所示:compile与sub组合替换掉已经匹配的字符串
2130
2330

被折叠的 条评论
为什么被折叠?
