How to find and replace nth occurrence of word in a sentence using python regular expression?

后端 未结 7 2393
广开言路
广开言路 2020-12-01 11:00

Using python regular expression only, how to find and replace nth occurrence of word in a sentence? For example:

str = \'cat goose  mouse horse pig cat cow\'         


        
7条回答
  •  眼角桃花
    2020-12-01 11:40

    Here's a way to do it without a regex:

    def replaceNth(s, source, target, n):
        inds = [i for i in range(len(s) - len(source)+1) if s[i:i+len(source)]==source]
        if len(inds) < n:
            return  # or maybe raise an error
        s = list(s)  # can't assign to string slices. So, let's listify
        s[inds[n-1]:inds[n-1]+len(source)] = target  # do n-1 because we start from the first occurrence of the string, not the 0-th
        return ''.join(s)
    

    Usage:

    In [278]: s
    Out[278]: 'cat goose  mouse horse pig cat cow'
    
    In [279]: replaceNth(s, 'cat', 'Bull', 2)
    Out[279]: 'cat goose  mouse horse pig Bull cow'
    
    In [280]: print(replaceNth(s, 'cat', 'Bull', 3))
    None
    

提交回复
热议问题