How to replace "$10" with "10 dollars" using regex?

0

Issue

I have some phrases like below:

This is not my spending '$10', this is companys spending: '$250 million' and this is some other figure: '$200,000'.

that I would like to remove the dollar symbols and add "dollar" at the end of phrase, like this:

This is not my spending '10 dollars', this is companys spending: '250 million dollars' and this is some other figure: '200000 dollars'.

I now have regex to match([£\$€][\s\d,\d]+(|million|billion|trillion)), but I haven’t been able to get the substitution part right.

How do I do this?

Solution

You may use the following function to achieve what you described.

import re

def adjust_dollars(text):
  text = re.sub(r'^\$', '', text)
  text = re.sub(r'(.$)', r'\1 dollars', text)
  return text

Test run:

words = ['$10', '$250 million', '$200,000']
result = map(adjust_dollars, words)
print(list(result))

Output:

['10 dollars', '250 million dollars', '200,000 dollars']

Answered By – Slybot

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More