Deutsch   English   Français   Italiano  
<v11gkh$9q5g$2@dont-email.me>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!weretis.net!feeder8.news.weretis.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Lawrence D'Oliveiro <ldo@nz.invalid>
Newsgroups: comp.lang.python
Subject: Re: Python Dialogs (Posting On Python-List Prohibited)
Date: Fri, 3 May 2024 02:02:57 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 24
Message-ID: <v11gkh$9q5g$2@dont-email.me>
References: <dialog-20240502150909@ram.dialup.fu-berlin.de>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Injection-Date: Fri, 03 May 2024 04:02:58 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="cfd0dd0a0e9abee8835016bed2d05754";
	logging-data="321712"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX18InmHwPNYLad0IzpunzP+f"
User-Agent: Pan/0.155 (Kherson; fc5a80b8)
Cancel-Lock: sha1:iZNKPiq7tPGCvS+EqJyEabYwUO0=
Bytes: 1763

> 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)
      )

result:

    'this be b test h eg'