1

I want something that replaces text between two occurences of the same string as follows:

Input:- "abcdefghcd","cd","k"
Output :- "abkefghk" 

You might think that a simple thing such a .replace() would work, but actually its not that. Some more examples-

Input:- "123*45","*","u"
Output:- "123*45" # No change because there aren't two occurences of "*"

Input:- "text*text*hello*text","*","k"
Output:- "textktextkhello*text"

I don't know how to do it. Any ideas?

0

3 Answers 3

2

Count the occurrences and only replace the first n-1 of them if n is odd.

>>> s, find, replace = "text*text*hello*text", "*", "k"
>>> s.replace(find, replace, 2*(s.count(find)//2))
'textktextkhello*text'
Sign up to request clarification or add additional context in comments.

Comments

0

what about splitting and joining :

Input = "abcdefghcd"
replace_="cd"
with_='k'


data=Input.split(replace_)
print(with_.join(data))

output:

abkefghk

1 Comment

This is nice idea, but it only works for the first case.
0

Split the string and only substitute pattern if more than 2 occurrences are found.

>>> replace = lambda s, pat, sub: "".join([x + sub for x in s.split(pat) if x]) if len(s.split(pat))>2 else s
>>> replace("abcdefghcd", "cd", "k")
'abkefghk'
>>> replace("123*45", "*", "u")
'123*45'

If you favor an explicit function (recommended) instead of a one-liner:

def replace(s, pat, sub, occ=2):
    """Return a string of replaced letters unless below the occurrences."""
    if len(s.split(pat)) > occ:
        return "".join([x + sub for x in s.split(pat) if x]) 
    return s

Comments

Your Answer

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