Insert some string into given string at given index

python, string

Solution

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.

Python's slice notation has a great answer explaining the subject of string slicing.

Problem

How can I insert some text into an existing string? For example, suppose I have a string `"Name Age Group Class Profession"`. How can I insert the third word three more times before the fourth, to get `"Name Age Group Group Group Group Class Profession"`? I know how to split the string into words using `.split()`, but then what?

Original source

Related problems