[Tutor] Python 3: string to decimal conversion

Alan Gauld alan.gauld at yahoo.co.uk
Sun May 22 11:44:54 EDT 2016


On 22/05/16 14:19, US wrote:

>>        with open(file) as csvfile:
>>            records = csv.reader(csvfile, quoting=csv.QUOTE_NONE)
> [...]
>>            for row in records:
> [...]
>>                try:
>>                    expenses[ts.Date(row[0]).month] +=
> decimal.Decimal(row[4])
>>                except ValueError:
>>                    pass

> I think the problem may be caused by an empty string value that is
> passed to decimal.Decimal function. The csv file contains some empty
> cells and I wanted the code to ignore them. That's why I had the
> ValueError exception.

If you know you are going to get some invalid data in your loop you
should test for it before the operation and use 'continue' to force the
loop to start the next iteration.  You could still catch the invalid
operation  error, just in case... Although, if you don't expect it and
don't know how to handle it then it's probably better to let Python just
do  its thing and give you the traceback.

Like this:

  with open(file) as csvfile:
     records = csv.reader(csvfile, quoting=csv.QUOTE_NONE)
       #...
       for row in records:
         if not row[4]:
             continue    # coz its empty
         else:
             expenses[ts.Date(row[0]).month] += decimal.Decimal(row[4])

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list