How to insert in a string @ a index

Ant antroy at gmail.com
Mon Sep 10 03:29:50 EDT 2007


On Sep 10, 3:15 am, "a.m." <lolu... at gmail.com> wrote:
> Thanks guys for you help. I ended up doing this way (for the
> records)...
>
> t1 = "hello world hello. hello. \nwhy world hello"
...

Another approach may be to use the re module's sub function:

import re

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

def matchHandler(match):
    if <test here>:
       return "XYZ" + match.group(0)
    else:
       return match.group(0)

re.sub(keyword, matchHandler, t1)

The nice thing about this approach is that you could store keyword:
test_function pairs in a dictionary, and reuse this whole block of
code for arbitrary keywords with arbitrary rules.

--
Ant...




More information about the Python-list mailing list