1

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
7
  • "||||".replace("|","|X") + '|' so just this then? Commented Oct 31, 2015 at 20:39
  • 1
    That gives '|X|X|X|X|' which adds an extra X Commented Oct 31, 2015 at 20:40
  • It seems like it might be better to reformulate your desired goal in terms other than overlapping substring replacement. For example, here, it looks like you want to insert text between delimiters, so something like a regex replace with lookahead and lookbehind assertions for a single | each would work. Commented Oct 31, 2015 at 20:42
  • What output would you want for '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. Commented Oct 31, 2015 at 20:44
  • "||||".replace("||","|X|X").strip('X') Commented Oct 31, 2015 at 20:49

1 Answer 1

3

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.