Insert some string into given string at given index
I am newbie in Python facing a problem: How to insert some fields in already existing string?
For example, suppose I have read one line from any file which contains:
line = "Name Age Group Class Profession"
Now I have to insert 3rd Field(Group) 3 times more in the same line before Class field. It means the output line should be:
output_line = "Name Age Group Group Group Group Class Profession"
I can retrieve 3rd field easily (using split
method), but please let me know the easiest way of inserting into the string?
Solution 1:
An important point that often bites new Python programmers but the other posters haven't made explicit is that strings in Python are immutable -- you can't 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 you're thinking "how can I create a new string that has some pieces from this one I've already gotten?"
Solution 2:
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.