Python Dialogs

Liste des GroupesRevenir à cl python 
Sujet : Python Dialogs
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.python
Date : 02. May 2024, 16: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!

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