How to insert in a string @ a index

Karthik Gurusamy kar1107 at gmail.com
Tue Sep 11 19:10:42 EDT 2007


On Sep 8, 11:02 am, lolu... at gmail.com wrote:
> Hi;
>
> I'm trying to insert XYZ before a keyword in a string. The first and
> the last occurence of hello in the string t1 (t1="hello world hello.
> hello \nwhy world hello") are keywords. So after the insertion of XYZ
> in this string, the result should be t1 = "XYZhello world hello. hello
> \nwhy world XYZhello"
>
> The python doesn't supports t1[keyword_index]="XYZhello" (string
> object assignment is not supported). How do I get to this problem? Any
> sugguestions?

Yet another solution using re

>>> t1 = 'hello world hello. hello. \nwhy world hello'

>>> import re
>>> l1 =  re.split('hello', t1)
>>> l1[0] = 'XYZ' + l1[0]
>>> l1[-2] += 'XYZ'
>>> 'hello'.join(l1)
'XYZhello world hello. hello. \nwhy world XYZhello'
>>>

If there are less than two 'hello', you'll get exception and needs
special handling.

Karthik

>
> -a.m.




More information about the Python-list mailing list