[Tutor] Python 3: string to decimal conversion

US usaidov at gmail.com
Sun May 22 09:19:19 EDT 2016


Thank you all for the useful feedback. I am new to programming so bear
with me while I learn the rules...


I have run Cameron's code to print the values and have the traceback
results. please see below.



-----Original Message-----
From: cs at zip.com.au [mailto:cs at zip.com.au]
Sent: Saturday, May 21, 2016 10:32 PM
To: Saidov <usaidov at gmail.com>
Cc: tutor at python.org
Subject: Re: [Tutor] Python 3: string to decimal conversion

Hi Saidov,

I'm going to reply to your post inline, as that is the etiquette here and
in many technical mailing lists.

On 21May2016 13:34, Saidov <usaidov at gmail.com> wrote:
>I am working on a piece of python code that's supposed to help me
>manage a
>budget:
>1. Read a banking statement
>2. Categorize expenses and income by month and by type 3. Print out a
>report comparing the projected expenses/income with actual numbers.

Thank you for providing your problem's context.

>*File characteristics:*
>Banking statement in a csv file format.
>contents: 5 columns, 1st column= date, 4 column=expenses date format:
>mm/dd/yyyy, type: string expenses format: ($0.00), type: string income
>format: $0.00, type: string
>
>*Python Version: 3.5 (64 bit)*
>IDE:Microsoft Visual Studio Community 2015 Version 14.0.25123.00 Update
>2
>
>Python Tools for Visual Studio   2.2.40315.00
>Python Tools for Visual Studio provides IntelliSense, projects,
>templates, Interactive windows, and other support for Python developers.

And this level of detail is very welcome.

>*Problem:*
> I want to convert expense/income values into a decimal form so I could
>sum them into appropriate buckets according to the month in which they
>occur. I am getting the following error message when I run my code:
>
>"decimal.InvalidOperation was unhandled by user code
>Message: [<class 'decimal.ConversionSyntax'>]"

Please always provide the full traceback which accompanied the exception
report; there should be a list of code lines indicating the call stack
where the error occurred. This provides valuable context for figuring out
where in your code to look for issues.

Absent that context, I will have a guess at where this might be occurring:

[...]
>files =['export.csv']
>with open("budgetfile.csv","wt") as fw:
>    writer = csv.writer(fw)
>    for file in files:
>        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 would guess that this:

  decimal.Decimal(row[4])

is the source of your error; it seems to be the only place where you
actually convert a string into a Decimal. I would guess that when handed a
bad string this raises decimal.ConversionSyntax instead of a ValueError.

I suggest that you print out the value of row[4] before the "try"
statement:

  print("row[4] =", repr(row[4]))

Note the use of repr: it gets you better detail about the value of the
string.

Thank you for a well presented question.

Finally, please try to post in plain text instead of rich text; this is a
plain text list and if you post in rich text or HTML (a) some hinting you
have have povided like coloured text will not be presented to readers and
(b) some things, particularly code, and be presented visually mangled,
which makes things hard to read and debug.

---------------------------------
+ decimal <module 'decimal' from 'C:\mypath\Anaconda3\\lib\\decimal.py'> module
+ expenses {1: Decimal('0'), 2: Decimal('0'), 3: Decimal('0'), 4:
Decimal('0'), 5: Decimal('0'), 6: Decimal('0'), 7: Decimal('0'), 8:
Decimal('0'), 9: Decimal('0'), 10: Decimal('0'), 11: Decimal('0'), 12:
Decimal('0')} dict
row[0] '"1/1/2016"' str
row[4] '""' str
+ ts <module 'timestring' from
'C:\mypath\Anaconda3\\lib\\site-packages\\timestring\\__init__.py'>
module

ipython traceback:

row[4]= ' "" '

Traceback (most recent call last):
  File "C:\mypath\visual studio
2015\Projects\Budget\Budget\Budget.py", line 28, in <module>
    expenses[ts.Date(row[0]).month] += decimal.Decimal(row[4])
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]


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.



------------------------------------------


Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Tutor mailing list