How can I parse this correctly?

Chris Angelico rosuav at gmail.com
Sun Apr 6 00:03:14 EDT 2014


On Sun, Apr 6, 2014 at 1:52 PM, Anthony Papillion <papillion at gmail.com> wrote:
> When I try to
> cast them like this:
>
> print int(row['YEAR'])
>
> I am told by the interpreter:
>
> Traceback (most recent call last):
>   File "analyze.py", line 14, in <module>
>     print int(row['MONTH'])
> ValueError: invalid literal for int() with base 10: ''
>
> What am I doing wrong? Am I not understanding HOW to cast?

An empty string isn't a valid Python integer, unlike in some other
languages where it's taken as zero. Do you have data in some but not
in others? Should all blank entries be interpreted as zero? (That's
common with a lot of spreadsheets.) Make sure that's really what you
want, and then just do this:

print int(row['MONTH'] or 0)

That'll set a default of zero, if (and only if) the MONTH string is blank.

By the way, is there a reason you're using Python 2 rather than Python
3? For new projects, you ideally should be working with a more recent
version of Python; that way, you won't have to edit your code later,
when you find there's some newer feature that you want. The
differences aren't huge, but the sooner you make the change, the less
code you have to look at.

ChrisA



More information about the Python-list mailing list