Python loves raising exceptions, which is usually great. But I’m facing some strings I desperately want to convert to integers using C’s atoi / atof semantics – e.g. atoi of “3 of 12”, “3/12”, “3 / 12”, should all become 3; atof(“3.14 seconds”) should become 3.14; atoi(” -99 score”) should become -99. Python of course has atoi and atof functions, which behave nothing like atoi and atof and exactly like Python’s own int and float constructors.
The best I have so far, which is really ugly and hard to extend to the various float formats available:
value = 1
s = str(s).strip()
if s.startswith("-"):
value = -1
s = s[1:]
elif s.startswith("+"):
s = s[1:]
try:
mul = int("".join(itertools.takewhile(str.isdigit, s)))
except (TypeError, ValueError, AttributeError):
mul = 0
return mul * value
It’s pretty straightforward to do this with regular expressions: