python-3.xsubstringpython-restring-substitution

Remove comma from substring in Python


The string is the following:

s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'

I would like the comma inside this substring "$1,455.85" to be removed but not the other commas.

I tried this but failed:

import re
pattern = r'$\d(,)'

re.sub(pattern, '', s)

Why doesn't this work?


Solution

  • You need a positive lookbehind assertion, i.e., match a comma if it is preceded by a $ (note that $ needs to be escaped as \$) followed by a digit (\d). Try:

    >>> s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
    >>> pattern = r'(?<=\$\d),'
    >>> re.sub(pattern, '', s)
    'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1455.85",($56.10),($56.10),-3.71%'