Insert a string before a substring of a string

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'

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


Why not use replace?

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

my_str.replace(substr, substr + inserttxt)
# 'thisissometextXXthatiwrote'

Tags:

Python

String