Python Dialogs
Sujet : Python Dialogs
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 02. May 2024, 15:23:19
Autres entêtes
Organisation : Stefan Ram
Message-ID : <dialog-20240502150909@ram.dialup.fu-berlin.de>
Me (indented by 2) and the chatbot (flush left). Lines lengths > 72!
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
s.replace(r"\ba\b", "b").replace(r"\bc\b", "d").replace(r"\be\b", "f").replace(r"\bg\b", "h")
No. "replace" will not use regular expressions, even if you write
"import re".
import re
s = re.sub(r"\ba\b", "b", s)
s = re.sub(r"\bc\b", "d", s)
s = re.sub(r"\be\b", "f", s)
s = re.sub(r"\bg\b", "h", s)
Now you give me a sequence of four statements, but I need an
expression!
s = re.sub(r"\ba\b", "b", re.sub(r"\bc\b", "d", re.sub(r"\be\b", "f", re.sub(r"\bg\b", "h", s))))
Yeah, that's an expression, but it's kind of nested I guess.
Can you write another expression with less nesting?
s = re.sub(r"\ba\b|\bc\b|\be\b|\bg\b", lambda x: {"a": "b", "c": "d", "e": "f", "g": "h"}[x.group()], s)
Nice idea! Only drawback is that to add another word, you gotta
modify in two places.
replacements = {"a": "b", "c": "d", "e": "f", "g": "h"}
s = re.sub(r"\b(" + "|".join(replacements.keys()) + r")\b", lambda x: replacements[x.group()], s)
PS: This is for the script I use to send posts. So if you do not
see "trying to" (5 letters: "t-r-y-n-a") here, it kind of worked!
Haut de la page
Les messages affichés proviennent d'usenet.
NewsPortal