Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!bawden.eternal-september.org!.POSTED!not-for-mail From: Alan Bawden Newsgroups: comp.lang.python Subject: Re: Python Dialogs (Posting On Python-List Prohibited) Date: Fri, 03 May 2024 03:16:35 -0400 Organization: ITS Preservation Society Lines: 35 Message-ID: <86v83vmkks.fsf@williamsburg.bawden.org> References: MIME-Version: 1.0 Content-Type: text/plain Injection-Date: Fri, 03 May 2024 09:16:38 +0200 (CEST) Injection-Info: bawden.eternal-september.org; posting-host="8c1c5e363e6bcb94508491a3ca9524fb"; logging-data="445037"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18igSM1+++rc9yECGptu9fX" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.4 (gnu/linux) Cancel-Lock: sha1:jARFzP3uSlY0SPhG+94F2WZXSVg= sha1:jkOh6o3xX8ODN1wqBNEMNb1uAcM= Bytes: 2042 Lawrence D'Oliveiro 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