Insert some string into given string at given index in Python


Question

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?

1
55
5/3/2016 5:13:51 PM

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?"

110
9/29/2016 3:02:57 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon