How to insert in a string @ a index

Karthik Gurusamy kar1107 at
Wed Sep 12 01:10:42 CEST 2007

On Sep 8, 11:02 am, lolu... at 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.


> -a.m.

More information about the Python-list mailing list