user2378481
user2378481

Reputation: 839

Insert a string before a substring of a string

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?

Upvotes: 17

Views: 43312

Answers (4)

santon
santon

Reputation: 4625

Why not use replace?

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

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

Upvotes: 20

Daniela Mazza
Daniela Mazza

Reputation: 1

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

(inserttxt+substr).join(**my_str**.split(substr))

Upvotes: 0

lord63. j
lord63. j

Reputation: 4670

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'

Upvotes: 10

Dušan Maďar
Dušan Maďar

Reputation: 9919

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

Upvotes: 32

Related Questions