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


Groups > comp.lang.python > #37571

Re: using split for a string : error

References <CAFqGZRGMXcku_nM_LqPsHpCzqGxF57LOSKwKwoCH+LyhPA8t_A@mail.gmail.com> <CAPTjJmpYi23Lx_4zuX28XURnAeaR-R=0w3e1mn6b0GBMs-O6Aw@mail.gmail.com> <51011822.3020702@tobix.eu>
Date 2013-01-24 22:35 +1100
Subject Re: using split for a string : error
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.969.1359027330.2939.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Jan 24, 2013 at 10:16 PM, Tobias M. <tm@tobix.eu> wrote:
> Chris Angelico wrote:
>> The other thing you may want to consider, if the values are supposed
>> to be integers, is to convert them to Python integers before
>> comparing.
>
> I thought of this too and I wonder if there are any major differences
> regarding performance compared to using the strip() method when parsing
> large files.
>
> In addition I guess one should catch the ValueError that might be raised by
> the cast if there is something else than a number in the file.

I'd not consider the performance, but the correctness. If you're
expecting them to be integers, just cast them, and specifically
_don't_ catch ValueError. Any non-integer value will then noisily
abort the script. (It may be worth checking for blank first, though,
depending on the data origin.)

It's usually fine to have int() complain about any non-numerics in the
string, but I must confess, I do sometimes yearn for atoi() semantics:
atoi("123asd") == 123, and atoi("qqq") == 0. I've not seen a
convenient Python function for doing that. Usually it involves
manually getting the digits off the front. All I want is to suppress
the error on finding a non-digit. Oh well.

ChrisA

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: using split for a string : error Chris Angelico <rosuav@gmail.com> - 2013-01-24 22:35 +1100
  Re: using split for a string : error Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-01-25 11:20 +1100
    Re: using split for a string : error Chris Angelico <rosuav@gmail.com> - 2013-01-25 12:07 +1100

csiph-web