2

I'm given a string my_str in Python. What I want to do is: If my_str contains a substring str1, then insert a string str2 right after the substring str1 (and leave the rest of my_str intact.) Otherwise, do nothing. (Let's say that my_str contains no more than one substring being str1.)

The way I'm thinking is: Do a for-loop to find whether str1 exists within my_str

for i in range(0, len(my_str)-len(str1)):
  if my_str[i:i+len(str1)] == str1:
    my_str = my_str[0:i] + str2 + my_str[i:]

I'm curious whether there's any magic way that can do this shorter.

1
  • 7
    Don't name a variable str or file or dict or set or list, etc Commented Nov 28, 2012 at 20:28

2 Answers 2

8

The easiest method is with str.replace():

>>> str1 = "blah"
>>> str2 = "new"
>>> "testblah".replace(str1, str1+str2)
'testblahnew'
>>> "testblahtest".replace(str1, str1+str2)
'testblahnewtest'
>>> "test".replace(str1, str1+str2)
'test'
>>> "blahtestblah".replace(str1, str1+str2)
'blahnewtestblahnew'

We simply replace the original value with the new string appended to itself, essentially slotting in the new value.

A quick tutorial on replace() for more examples.

Sign up to request clarification or add additional context in comments.

Comments

1
def myReplace(myStr, str1, str2):
    try:
        i = myStr.index(str1)
        answer = myStr[:i+len(str1)] + str2 + myStr[i+len(str1):]
        return answer
    except ValueError:
        return myStr

Hope this helps

4 Comments

honest question- what is the advantage of doing it this way rather than using the built-in replace method?
@Anov: the built-in replace is what I would normally go with. Since the OP seems to be a beginner, I gave an answer that's closer to what he was trying to implement. I would have the replace way of doing this in my answer to be complete, but as I finished writing this solution, I noticed that someone else had posted that already.
@inspectorG4dget In think you used the try-except to handle ValueError, if that's the case then use str.find(), it returns -1 if the substring is not found.
The OP's version will replace every instance of str1 with str1+str2; yours will only replace the first. The OP said "Let's say that my_str contains no more than one substring being str1", but it's worth pointing out the difference. With replace, you can do it either way—pass 1 for count, or don't. You could also do the same with this solution by adding a loop and passing i+1 as the start to each index/find call.

Your Answer

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.