Efficient repeated substring replace with Python
Question: How can I efficiently replace substrings in python, where one substring may be
part of another? For example:

    
    
    >>> "||||".replace("||","|X|")
    '|X||X|'
    # What I want: |X|X|X|
    

Certainly I could keep repeating the replace and until there are no more
instances of `||` in the string, but surely there's a better/faster way?


Answer: In general you need to repeat the process.

In this specific case however you can use a regexp to insert `X` between
consecutive `|` signs:

    
    
    import re
    print(re.sub("[|](?=[|])",
                 "|X",
                 "||||"))
    

meaning is "replace any pipe with pipe+X if what follows is another pipe (but
don't consider it part of the match)"

