subn
的非正则表达式等价物是什么?我想替换字符串中的模式,并计算该模式被替换了多少次。
最后我得到了:
def replacen(pat, repl, txt):
txt2 = txt.replace(pat, repl)
if (len(pat) != len(repl)):
return (txt2, (len(txt) - len(txt2)) / (len(pat) - len(repl)))
else:
return (txt2, txt.count(pat))
有没有更优雅的解决方案?在
Tags:
您自己的代码可以简单地返回txt2和模式计数:
如果没有被替换,那是因为您没有找到匹配的子字符串,所以count将返回
0
如果您替换了5substring/pats
,那么txt.count(帕特)会给你5分相关问题 更多 >
编程相关推荐