Search code examples
pythonpython-re

Expand currency sign with moving words inside string


How can I achieve this without using if operator and huge multiline constructions?

Example:

around $98 million last week
above $10 million next month
about €5 billion past year
after £1 billion this day

Convert to

around 98 million dollars last week
above 10 million dollars next month
about 5 billion euros past year
after 1 billion pounds this day

Solution

  • You probably have more cases than this so the regular expression may be too specific if you have more cases, but re.sub can be used with a function to process each match and make the correct replacement. Below solves for the cases provided:

    import re
    
    text = '''\
    around $98 million last week
    above $10 million next month
    about €5 billion past year
    after £1 billion this day
    '''
    
    currency_name = {'$':'dollars', '€':'euros', '£':'pounds'}
    
    def replacement(match):
        # group 2 is the digits and million/billon,
        # tack on the currency type afterward using a lookup dictionary
        return f'{match.group(2)} {currency_name[match.group(1)]}'
    
    # capture the symbol followed by digits and million/billion
    print(re.sub(r'([$€£])(\d+ [mb]illion)\b', replacement, text))
    

    Output:

    around 98 million dollars last week
    above 10 million dollars next month
    about 5 billion euros past year
    after 1 billion pounds this day