using split for a string : error

Chris Angelico rosuav at gmail.com
Thu Jan 24 06:35:22 EST 2013


On Thu, Jan 24, 2013 at 10:16 PM, Tobias M. <tm at 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



More information about the Python-list mailing list