Thanks guys for you help. I ended up doing this way (for the records)... t1 = "hello world hello. hello. \nwhy world hello" while index<t1.count("hello"): if (your condition to determine keyword): t2=t1[:(index+offset)].replace("hello","XYZhello")+t1[((index +offset):] # offset is 5 (hello = 5 characters) index+=1