Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #69738 > unrolled thread

Re: How can I parse this correctly?

Started byChris Angelico <rosuav@gmail.com>
First post2014-04-06 14:03 +1000
Last post2014-04-06 14:03 +1000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: How can I parse this correctly? Chris Angelico <rosuav@gmail.com> - 2014-04-06 14:03 +1000

#69738 — Re: How can I parse this correctly?

FromChris Angelico <rosuav@gmail.com>
Date2014-04-06 14:03 +1000
SubjectRe: How can I parse this correctly?
Message-ID<mailman.8933.1396757395.18130.python-list@python.org>
On Sun, Apr 6, 2014 at 1:52 PM, Anthony Papillion <papillion@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web