Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Multiple string.replace()

Name: Anonymous 2010-03-18 21:06

I'm trying to search and replace words in a long string in FIOC.


(pseudocode)
for i between 0 and 10:
  str = str.replace(words[i], replacements[i])


However, since strings are immutable, the string is copied each time and is slow. Since the length of the words are exactly the same as the replacements, I would like to edit the original string directly. Is that possible somehow?

Name: Anonymous 2010-03-24 20:46


import re
def multiple_replace(text,adict):
    rx = re.compile('|'.join(map(re.escape, adict)))
    def one_xlat(match):
        return adict[match.group(0)]
    return rx.sub(one_xlat, text)

text = "ABC abcAbc"
adict = { "abc" : "def" }

print multiple_replace(text,adict)

...gives me "ABC defAbc"

I need to make it case insensitive. Where do I put re.I?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List