Replace nth occurrence of substring in string

后端 未结 10 2365
面向向阳花
面向向阳花 2020-11-27 06:51

I want to replace the n\'th occurrence of a substring in a string.

There\'s got to be something equivalent to what I WANT to do which is

mystring.repl

10条回答
  •  独厮守ぢ
    2020-11-27 07:24

    I have come up with the below, which considers also options to replace all 'old' string occurrences to the left or to the right. Naturally, there is no option to replace all occurrences, as standard str.replace works perfect.

    def nth_replace(string, old, new, n=1, option='only nth'):
        """
        This function replaces occurrences of string 'old' with string 'new'.
        There are three types of replacement of string 'old':
        1) 'only nth' replaces only nth occurrence (default).
        2) 'all left' replaces nth occurrence and all occurrences to the left.
        3) 'all right' replaces nth occurrence and all occurrences to the right.
        """
        if option == 'only nth':
            left_join = old
            right_join = old
        elif option == 'all left':
            left_join = new
            right_join = old
        elif option == 'all right':
            left_join = old
            right_join = new
        else:
            print("Invalid option. Please choose from: 'only nth' (default), 'all left' or 'all right'")
            return None
        groups = string.split(old)
        nth_split = [left_join.join(groups[:n]), right_join.join(groups[n:])]
        return new.join(nth_split)
    

提交回复
热议问题