Lawrence D'Oliveiro <ldo@nz.invalid> writes:

   > Assume you have an expression "s.replace('a','b').replace('c','d').
   > replace('e','f').replace('g','h')". Its value is a string which
   > is the value of s, but with "a" replaced by "b", "c" replaced by
   > "d", "e" replaced by "f" and "g" replaced by "h". How to modify
   > this expression, so that "a", "c", "e", and "g", respectively,
   > are replaced only if they are words (but not parts of words)?

       import re

       replacements = (("a", "b"), ("c", "d"), ("e", "f"), ("g", "h"))

       text = "this be a test g eg"

       "".join \
         (
           repl.get(s, s)
           for repl in (dict(replacements),)
           for s in
               re.split("\\b(" + "|".join(re.escape(s[0]) for s in 
replacements) + ")\\b", text)
         )

How about just:

  repl = {
      "a" : "b",
      "c" : "d",
      "e" : "f",
      "g" : "h",
  }

  "".join(repl.get(s, s) for s in re.split(r"\b", text))

- Alan
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to