Does anybody have a quickie for converting an unsafe string to an int
?
The string typically comes back as: '234\r\n'
or something like that.
In this case I want 234
. If '-1\r\n'
, I want -1
. I never want the method to fail but I don't want to go so far as try, except, pass just to hide errors either (in case something extreme happens).
import re
int(re.sub(r'[^\d-]+', '', your_string))
This will strip everything except for numbers and the "-" sign. If you can be sure that there won't be ever any excess characters except for whitespace, use gruszczy's method instead.
In this case you do have a way to avoid try
/except
, although I wouldn't recommend it (assuming your input string is named s
, and you're in a function that must return something):
xs = s.strip()
if xs[0:1] in '+-': xs = xs[1:]
if xs.isdigit(): return int(s)
else: ...
the ...
part in the else
is where you return whatever it is you want if, say, s
was 'iamnotanumber'
, '23skidoo'
, empty, all-spaces, or the like.
Unless a lot of your input strings are non-numbers, try/except is better:
try: return int(s)
except ValueError: ...
you see the gain in conciseness, and in avoiding the fiddly string manipulation and test!-)
I see many answers do int(s.strip())
, but that's supererogatory: the stripping's not needed!
>>> int(' 23 ')
23
int
knows enough to ignore leading and trailing whitespace all by itself!-)
int('243\r\n'.strip())
But that won't help you, if something else than a number is passed. Always put try, except and catch ValueError
.
Anyway, this also works: int('243\n\r ')
, so maybe you don't even need strip
.
EDIT:
Why don't you just write your own function, that will catch the exception and return a sane default and put into some utils module?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With