Regural expression puzzle for gurus

Pekka Niiranen krissepu at vip.fi
Fri Jul 13 09:18:46 CEST 2001


I have a string in the middle of a text starting with #-sign and ending
to \W.
I can find it with re.compile('#\w+') and  would like to replace it by
adding a
# -sign also to the end of it.

Example:

            original string:           xx:yy:#AAA.!:-#BBB:2324:#CCC:!"¤%

            after replacement:    xx:yy:#AAA#.!:-#BBB#:2324:#CCC#:!"¤%

How can I do replacement with a single regural expression line ?

I have found a solution like:
           text = 'xx:yy:#AAA:-#BBB:aa'
           line = re.compile('#\w+')
           list = line.findall(text)
           for i in range(len(list)):
                 text = text.replace(list[i],list[i]+'#')

>>>  text
'xx:yy:#AAA#:-#BBB#:aa'

I would like to do this without the for -loop (unless somebody can
convince
me the found solution is the fastest available)




More information about the Python-list mailing list