I have built a "Currency Tagger" in Python which identifies all currency expressions and replaces them with a tagged string.
Example,
replace "I have $20 in my pocket"
with "I have <Currency>$20</Currency> in my pocket"
One of the tasks requires me to substitute the string identified as Currency with the tagged string. I am using re.sub() to do this.
It works perfectly for every form of string except of the form "$4.4B" or "$4.4M".
I tried running simple example in my python console and found that re.sub() works inconsistently with patterns which have a mixed dollar pattern.
For example,
>>> text = "I have #20 in my pocket"
>>> re.sub("#20", "$20", text)
'I have $20 in my pocket'
>>> text = "I have $20 in my pocket"
>>> re.sub("$20", "#20", text)
'I have $20 in my pocket'
In the above example you see that when I am trying to replace "$20" with "#20" it does not work (in the second case).
Any help would be greatly appreciated of course. A very silly bug has cropped up and is stalling major work because of this.
$ is a special character .So if you want to replace it use
re.sub(r"\$20", "#20", text)
^^
You will have to escape it.Also use r mode to avoid escaping problems.
$ means end of string.So your regex was being ineffective.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With