python – Insert some string into given string at given index
python – Insert some string into given string at given index
An important point that often bites new Python programmers but the other posters havent made explicit is that strings in Python are immutable — you cant ever modify them in place.
You need to retrain yourself when working with strings in Python so that instead of thinking, How can I modify this string? instead youre thinking how can I create a new string that has some pieces from this one Ive already gotten?
For the sake of future newbies tackling this problem, I think a quick answer would be fitting to this thread.
Like bgporter said: Python strings are immutable, and so, in order to modify a string you have to make use of the pieces you already have.
In the following example I insert Fu
in to Kong Panda
, to create Kong Fu Panda
>>> line = Kong Panda
>>> index = line.find(Panda)
>>> output_line = line[:index] + Fu + line[index:]
>>> output_line
Kong Fu Panda
In the example above, I used the index value to slice the string in to 2 substrings:
1 containing the substring before the insertion index, and the other containing the rest.
Then I simply add the desired string between the two and voilĂ , we have inserted a string inside another.
Pythons slice notation has a great answer explaining the subject of string slicing.
python – Insert some string into given string at given index
I know its malapropos, but IMHO easy way is:
def insert (source_str, insert_str, pos):
return source_str[:pos]+insert_str+source_str[pos:]