Re: Python Dialogs (Posting On Python-List Prohibited)

Liste des GroupesRevenir à cl python 
Sujet : Re: Python Dialogs (Posting On Python-List Prohibited)
De : alan (at) *nospam* csail.mit.edu (Alan Bawden)
Groupes : comp.lang.python
Date : 03. May 2024, 09:16:35
Autres entêtes
Organisation : ITS Preservation Society
Message-ID : <86v83vmkks.fsf@williamsburg.bawden.org>
References : 1 2
User-Agent : Gnus/5.13 (Gnus v5.13) Emacs/24.4 (gnu/linux)
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

Date Sujet#  Auteur
2 May 24 * Python Dialogs11Stefan Ram
2 May 24 +* Re: Python Dialogs8Loris Bennett
4 May 24 i+- Re: Python Dialogs1Peter J. Holzer
6 May 24 i`* Re: Python Dialogs6jak
6 May 24 i +* Re: Python Dialogs4Stefan Ram
6 May 24 i i+* Re: Python Dialogs2Stefan Ram
6 May 24 i ii`- Re: Python Dialogs1jak
6 May 24 i i`- Re: Python Dialogs (Posting On Python-List Prohibited)1Lawrence D'Oliveiro
6 May 24 i `- Re: Python Dialogs1Chris Angelico
3 May 24 `* Re: Python Dialogs (Posting On Python-List Prohibited)2Lawrence D'Oliveiro
3 May 24  `- Re: Python Dialogs (Posting On Python-List Prohibited)1Alan Bawden

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal