replacing only single instances of a character with python regexp

notes, if not using a callable for the replacement function:

  • you would need look-ahead because you must not match if followed by $
  • you would need look-behind because you must not match if preceded by $

not as elegant but this is very readable:

>>> def dollar_repl(matchobj):
...     val = matchobj.group(0)
...     if val == '$':
...         val="z"
...     return val
... 
>>> import re
>>> s="$a $$b $$$c $d"
>>> re.sub('\$+', dollar_repl, s)
'za $$b $$$c zd'

Leave a Comment