1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
user8270077
  • 4,621
  • 17
  • 75
  • 140

2 Answers2

2

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%'
Nikolaos Chatzis
  • 1,947
  • 2
  • 8
  • 17
0
import re
pattern = r"(\$\d+),"
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
print(s)
s = re.sub(pattern, r'\1', s)
print(s)

Output:

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

But it doesn't work for "$1,455,789.85"

Malar B
  • 1
  • 1
  • Please explain what your code does and how it does it. And if it doesn't work for certain inputs, then it is not the correct answer. – M-Chen-3 Dec 10 '20 at 01:11