[Tutor] Python 3: string to decimal conversion

Peter Otten __peter__ at web.de
Tue May 24 03:59:48 EDT 2016


cs at zip.com.au wrote:

> On 23May2016 12:18, Saidov <usaidov at gmail.com> wrote:
>>Thanks everyone for all your help. This solved my problem with
>>parenthesis and $ signs in the data:
>>
>>if not row[4]:
>>                    pass
>>                else:
>>                    try:
>>                        expenses[ts.Date(row[0]).month] +=
>>decimal.Decimal(row[4].strip('()$ ,').replace(',',''))
>>                    except decimal.InvalidOperation as e:
>>                        print("unexpected expenses value:  %r" % (row[4]))
> 
> These are three things to remark on with your new code:

Noughtily?

Whatever you do, the conversion is complex enough to put it into a separate 
function. This makes it easier to test the code against typical input and 
corner cases.

> Firstly, it is best to put try/except around as narrow a piece of code as 

[...] 




More information about the Tutor mailing list