How can I parse this correctly?

Anthony Papillion papillion at gmail.com
Sun Apr 6 02:29:43 EDT 2014


On Apr 5, 2014, at 23:03, Chris Angelico <rosuav at gmail.com> wrote:

> 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.

Many thanks! That's exactly what I was looking for. In this case,  
since I'm needing to create a valid date, I'm defaulting to 1.

> 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

No particular reason at all. I've Bern dabbling in Python for the last  
bit and am just writing code based on the samples or examples I'm  
finding.  What was the tipoff that this was not Python 3? Would there  
be a large difference in this code if it was Python 3?

Anthony



More information about the Python-list mailing list