Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert substring if found

Tags:

python

string

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.

like image 403
JJ Beck Avatar asked Mar 20 '26 21:03

JJ Beck


1 Answers

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.

like image 64
Gareth Latty Avatar answered Mar 22 '26 10:03

Gareth Latty