Apex Predator
Apex Predator

Reputation: 171

how to convert currency in python file

Hi so i have this file here; i need to do is change the currency from dollar to euro; which will be on the right unlike the dollar sign on the left so i read the file and i write in a new one with the euro currency. sorry if it's messy. i got it WORKING once but i closed python shell not knowing that i would have to face another. problem here is the file and my code

menu = []
myString = ''

with open("menu.txt", "r") as ins:
    array = [] 
    for line in ins:
        array.append(line)
        myArray = line.split()
        myArray[len(myArray)-2] = str(float(myArray[len(myArray)-1])*0.75)
        myArray[len(myArray)-1] = 'euros'
        menu.append(myArray)
        myString+=(" ".join(myArray))
        myString+= " " + " \n"

f = open('EuroMenu.txt','w')
f.write(myString) 

expected output: grilled romaine, tomato jam, ricotta 9.75 euros. and so on with the rest; so each line should be display with the price in euro

current outputs

Traceback (most recent call last):
  File "<pyshell#113>", line 6, in <module>
    myArray[len(myArray)-2] = str(float(myArray[len(myArray)-1])*0.75)
ValueError: could not convert string to float: 'Végétarien'

it's just one of them, i tried different things

file

Végétarien #it's french :)
grilled romaine, tomato jam, ricotta $13.
potato leek soup $8. 
marinated fig, pistachio, boston scarlet $14. 
grilled romaine, tomato jam, ricotta $13.
gnocchi mushroom and cherry tomato $15. 

meat
beef tartare, wasabi mayo $16. 
lamb merguez, cauliflower, cabbage $16.
boar sausage and bourbon mustard $15. 
confit rabbit, orzo $15. 
lamb berbere and lentil $13.
grilled hanger steak, frites, aioli $16.

Upvotes: 0

Views: 1000

Answers (2)

cdarke
cdarke

Reputation: 44364

In an attempt to keep as close to your code as possible:

import re

f = open('EuroMenu.txt','w')

with open("menu.txt", "r") as ins:
    for line in ins:
        myArray = line.split()

        if myArray:
            m = re.search(r'\$(\d+(?:\.\d{1,2})?)\.?$', myArray[-1])
            if m:
                amount = m.groups()[0]
                myArray[-2] = str(float(amount)*0.75)
                myArray[-1] = 'euros'

        f.write(" ".join(myArray) + " \n")

f.close()

Here is an explanation of the regular expression:

r'                        # use a raw string
   \$                     # search for a literal $
     (                    # capture this group, text become m.groups()[0]
      \d+                 # one of more digits
         (?:\.\d{1,2})?   # non-capture, allow for optional cents
     )                    # end of first capture group
      \.?$                # optional . at end-of-line
'                         # end of raw string

You don't really need a list ("array"), but if you do need the right-most element, use myArray[-1], not myArray[len(myArray)-1].

You were originally appending to a string then writing the whole lot out in one go. Appending to a string creates a new string object each time you do it (it doesn't actually "append", although that can be implementation specific). It is tidier to write each line out as you go.

I couldn't figure out why you had the menu or array lists.

By the way, you can get the euro currency symbol by using (python 2)

euro = unichr(0x20ac)

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174622

You can do this easily by using regular expressions:

>>> le_menu = '''Végétarien #it's french :)
... potato leek soup $8.
... marinated fig, pistachio, boston scarlet $14.
... grilled romaine, tomato jam, ricotta $13.
... gnocchi mushroom and cherry tomato $15.
...
... meat
... beef tartare, wasabi mayo $16.
... lamb merguez, cauliflower, cabbage $16.
... boar sausage and bourbon mustard $15.
... confit rabbit, orzo $15.
... lamb berbere and lentil $13.
... grilled hanger steak, frites, aioli $16.'''
>>> import re
>>> print(re.sub(r'\$(\d+)', lambda x: '{} EUR'.format(x.groups()[0]), le_menu, flags=re.M))
Végétarien #it's french :)
potato leek soup 8 EUR.
marinated fig, pistachio, boston scarlet 14 EUR.
grilled romaine, tomato jam, ricotta 13 EUR.
gnocchi mushroom and cherry tomato 15 EUR.

meat
beef tartare, wasabi mayo 16 EUR.
lamb merguez, cauliflower, cabbage 16 EUR.
boar sausage and bourbon mustard 15 EUR.
confit rabbit, orzo 15 EUR.
lamb berbere and lentil 13 EUR.
grilled hanger steak, frites, aioli 16 EUR.

Upvotes: 1

Related Questions