python:不带正则表达式的字符串中计数和替换模式

2024-10-02 20:37:24 发布

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

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: 字符串txtlenreturnifdefcount模式
1条回答
网友
1楼 · 发布于 2024-10-02 20:37:24

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

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

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

相关问题 更多 >