5

is there a similar function in python that takes search(array) and replace(array) as a parameter? Then takes a value from each array and uses them to do search and replace on subject(string).

I know I can achieve this using for loops, but just looking more elegant way.

1

4 Answers 4

14

I believe the answer is no.

I would specify your search/replace strings in a list, and the iterate over it:

edits = [(search0, replace0), (search1, replace1), (search2, replace2)] # etc.
for search, replace in edits:
    s = s.replace(search, replace)

Even if python did have a str_replace-style function, I think I would still separate out my search/replace strings as a list, so really this is only taking one extra line of code.

Finally, this is a programming language after all. If it doesn't supply the function you want, you can always define it yourself.

4
  • 1
    yes, you are rigth. but builtin functions tend to be more efficient.
    – Mohamed
    Sep 8, 2009 at 0:53
  • The problem with this solution is that edit #2 might replace something inserted by the edits before it, which I would expect to be absolutely to avoid. Sep 8, 2009 at 0:53
  • @kaizer.se: Yes, this is true. I don't know PHP but nz.php.net/str_replace says: "If search or replace are arrays, their elements are processed first to last." Only replacing non-overlapping search strings would be a difficult problem, I think.
    – John Fouhy
    Sep 8, 2009 at 1:01
  • 3
    @Ainab: Sure, but remember what they say about premature optimization. I expect this simple code to be fast enough for most situations. If you've profiled it and you need more speed, you could ask another question: "How can I speed this up?"
    – John Fouhy
    Sep 8, 2009 at 1:05
2

Heh - you could use the one-liner below whose elegance is second only to its convenience :-P

(Acts like PHP when search is longer than replace, too, if I read that correctly in the PHP docs.):

**** Edit: This new version works for all sized substrings to replace. ****

>>> subject = "Coming up with these convoluted things can be very addictive."
>>> search = ['Coming', 'with', 'things', 'addictive.', ' up', ' these', 'convoluted ', ' very']
>>> replace = ['Making', 'Python', 'one-liners', 'fun!']
>>> reduce(lambda s, p: s.replace(p[0],p[1]),[subject]+zip(search, replace+['']*(len(search)-len(replace))))
'Making Python one-liners can be fun!'
1
  • Neat. Itertools can continue sequences better: def cont(seq, elem=None): return itertools.chain(seq, itertools.repeat(elem)); now use cont(replace, '') Sep 8, 2009 at 13:11
1

Do it with regexps:

import re

def replace_from_list(replacements, str):
    def escape_string_to_regex(str):
        return re.sub(r"([\\.^$*+?{}[\]|\(\)])", r"\\\1", str)

    def get_replacement(match):
        return replacements[match.group(0)]

    replacements = dict(replacements)
    replace_from = [escape_string_to_regex(r) for r in replacements.keys()]
    regex = "|".join(["(%s)" % r for r in replace_from])
    repl = re.compile(regex)

    return repl.sub(get_replacement, str)

# Simple replacement:
assert replace_from_list([("in1", "out1")], "in1") == "out1"

# Replacements are never themselves replaced, even if later search strings match
# earlier destination strings:
assert replace_from_list([("1", "2"), ("2", "3")], "123") == "233"

# These are plain strings, not regexps:
assert replace_from_list([("...", "out")], "abc ...") == "abc out"

Using regexps for this makes the searching fast. This won't iteratively replace replacements with further replacements, which is usually what's wanted.

0

Made a tiny recursive function for this

def str_replace(sbjct, srch, rplc):
    if len(sbjct) == 0:
        return ''

    if len(srch) == 1:
        return sbjct.replace(srch[0], rplc[0])

    lst = sbjct.split(srch[0])
    reslst = []
    for s in lst:
        reslst.append(str_replace(s, srch[1:], rplc[1:]))
    return rplc[0].join(reslst);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.