How to replace a comma

Nick Craig-Wood nick at craig-wood.com
Mon Dec 18 10:30:06 EST 2006


Lad <python at hope.cz> wrote:
>  In a text I need to add a blank(space) after a comma but only if
>  there was no blank(space) after the comman If there was a
>  blank(space), no change is made.
> 
>  I think it could be a task for regular expression but can not
>  figure out the correct regular expression.

You can do it with a zero width negative lookahead assertion, eg

  >>> import re
  >>> s="One, Two,Three,Four, File"
  >>> re.sub(r",(?!\s)", ", ", s)
  'One, Two, Three, Four, File'
  >>> 

>From the help :-

  (?!...)
      Matches if ... doesn't match next. This is a negative lookahead
      assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if
      it's not followed by 'Asimov'

Or in a more straightforward but less efficient and accurate style -
this matches the next character which gets added back into the string.

  >>> re.sub(r",([^\s])", r", \1", s)
  'One, Two, Three, Four, File'
  >>> 

This shows a fundamental difference between the two methods

  >>> t = ",,,,,"
  >>> re.sub(r",(?!\s)", ", ", t)
  ', , , , , '
  >>> re.sub(r",([^\s])", r", \1", t)
  ', ,, ,,'
  >>>

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list