ttomwright
ttomwright

Reputation: 3

Use of int(str)

I was wondering if there is a much easier way to do this?

if '0' in next or '1' in next or '2' in next or '3' in next or '4' in next or '5' in next or '6' in next or '7' in next or '8' in next or '9' in next:
        how_much = int(next)

Upvotes: 0

Views: 87

Answers (2)

NightShadeQueen
NightShadeQueen

Reputation: 3334

If for some reason you didn't feel like using exception handling and wanted to use a regex instead:

re_is_int=re.compile('-?\d+$') #-? possible negative sign
                             #\d -> is digit.
                             #+ -> at least one. In this case, at least one digit.
                             #$ -> end of line.
                             #Not using '^' for start of line because I can just use re.match for that.
if re_is_int.match(next): #do rename this variable, you're shadowing the builtin next
                          #re.match only matches for start of line.
    how_much = int(next)

I haven't profiled this approach compared to Martijn's; I'd suspect that his would fare much better if your input was mostly numbers, and mine would fare better if it was mostly not numbers, but frankly if you cared about performance that much anyways, you either wouldn't be using python or you'd be profiling everything.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121436

Use exception handling; ask for forgiveness rather than permission:

try:
    how_much = int(next)
except ValueError:
    # handle the conversion failing; pass means 'ignore'
    pass

Upvotes: 5

Related Questions