17

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?

3

4 Answers 4

33
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

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

Comments

20

Why not use replace?

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

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

2 Comments

In Python .replace() returns a copy of string, so I guess it should be: new_str = my_str.replace(substr, substr + inserttxt)
This is confusing it replaces text with textXX
10

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'

2 Comments

could you add an explanation?
@Robert using str.split(substr) to split str to ['thisissome', 'thatiwrote'], and then we join them with "XXtext" ((inserttxt+substr)).
0

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

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

Comments

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.