14

I want to insert some text before a substring in a string.

For example:

str = "thisissometextthatiwrote"
substr = "text"
inserttxt = "XX"

I want:

str = "thisissomeXXtextthatiwrote"

Assuming substr can only appear once in str, how can I achieve this result? Is there some simple way to do this?

user2378481
  • 789
  • 1
  • 9
  • 17
  • Take a look at this answer http://stackoverflow.com/a/24450558/1326943 – CJ4 May 14 '15 at 08:11
  • possible duplicate of [how to insert some string in the given string at given index in python](http://stackoverflow.com/questions/4022827/how-to-insert-some-string-in-the-given-string-at-given-index-in-python) – Dhinakaran Thennarasu May 14 '15 at 08:14
  • @DhinakaranThennarasu it's not a dupe of that one, because that one doesn't ask how to find the index of substr – GreenAsJade May 14 '15 at 09:31

4 Answers4

26
my_str = "thisissometextthatiwrote"
substr = "text"
inserttxt = "XX"

idx = my_str.index(substr)
my_str = my_str[:idx] + inserttxt + my_str[idx:]

ps: avoid using reserved words (i.e. str in your case) as variable names

Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
16

Why not use replace?

my_str = "thisissometextthatiwrote"
substr = "text"
inserttxt = "XX"

my_str.replace(substr, substr + inserttxt)
# 'thisissometextXXthatiwrote'
santon
  • 4,395
  • 1
  • 24
  • 43
9

Use str.split(substr) to split str to ['thisissome', 'thatiwrote'], since you want to insert some text before a substring, so we join them with "XXtext" ((inserttxt+substr)).

so the final solution should be:

>>>(inserttxt+substr).join(str.split(substr))
'thisissomeXXtextthatiwrote'

if you want to append some text after a substring, just replace with:

>>>(substr+appendtxt).join(str.split(substr))
'thisissometextXXthatiwrote'
lord63. j
  • 4,500
  • 2
  • 22
  • 30
0

With respect to the question (were ´my_str´ is the variable), the right is:

(inserttxt+substr).join(**my_str**.split(substr))
glennsl
  • 28,186
  • 12
  • 57
  • 75