Skip to main content
 首页 » 编程设计

python:在没有正则表达式的情况下计算和替换字符串中的模式

2024年10月24日28lonelyxmas

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)) 

有没有更优雅的解决方案?

请您参考如下方法:

您自己的代码可以简单地返回 txt2 和模式的计数:

def replacen(pat, repl, txt): 
    txt2 = txt.replace(pat, repl) 
    return txt2, txt.count(pat) 

如果没有任何内容被替换,那是因为您没有找到匹配的子字符串,所以如果您替换了 5 个 substring/pats,那么 count 将返回 0,那么 txt.count(pat) 是会给你 5