Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert a string to an integer

Tags:

python

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).

like image 787
Adam Nelson Avatar asked Mar 24 '10 15:03

Adam Nelson


3 Answers

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.

like image 112
Ludwik Trammer Avatar answered Nov 20 '22 07:11

Ludwik Trammer


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!-)

like image 24
Alex Martelli Avatar answered Nov 20 '22 06:11

Alex Martelli


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?

like image 8
gruszczy Avatar answered Nov 20 '22 08:11

gruszczy