views:

66

answers:

4

Hi, I am newbie in python and facing some problem , my problem is that 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 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 insertion in the string

A: 

Split the string into fields, add three times the 'Group' element and then join with spaces:

line = 'Name Age Group Class Profession'
fields = line.split()
fields[2:2] = [fields[2]] * 3
output_line = ' '.join(fields)
eumiro
A: 
line='Name Age Group Class Profession'
arr = line.split()
for i in range(3):
    arr.insert(2, arr[2])
print(' '.join(arr))
Michał Niklas
A: 

There are several ways to do this:

One way is to use slicing:

>>> a="line=Name Age Group Class Profession"
>>> b=a.split()
>>> b[2:2]=[b[2]]*3
>>> b
['line=Name', 'Age', 'Group', 'Group', 'Group', 'Group', 'Class', 'Profession']
>>> a=" ".join(b)
>>> a
'line=Name Age Group Group Group Group Class Profession'

Another would be to use regular expressions:

>>> import re
>>> a=re.sub(r"(\S+\s+\S+\s+)(\S+\s+)(.*)", r"\1\2\2\2\2\3", a)
>>> a
'line=Name Age Group Group Group Group Class Profession'
Tim Pietzcker
+3  A: 

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

bgporter
+1 for mentioning the correct implementation.
anand
+1 Same Applies for Java. :)
st0le