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?
asked Oct 31, 2015 at 20:37
1 Answer 1
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)"
answered Oct 31, 2015 at 20:45
lang-py
"||||".replace("|","|X") + '|'
so just this then?|
each would work.'aaaa'.replace('aaa', 'pony')
? There are two overlapping instances of'aaa'
in the input, but it doesn't really make sense to replace both of them."||||".replace("||","|X|X").strip('X')