This code was in discussion of getting numeric input to Python.
This function returns the zero-stripped, normalized string form the input string if it is correct, False truth value otherwise (it can not be mixed with number 0 as accepted '0' are returned as string '0').
If string passes the test, it can safely be changed to float by the float function, without causing exception.
More lazy way of implement this is by try..except:
## scanum checks that number is ok, does not yet recognize enginering format (e.g. 1e7) from __future__ import print_function import random def scanum(x): try: v=float(x) return x except: return False ## do some random testing num = 4000 chars = 20 ok = 0 for x in range(num): i = ''.join([x and i for x in range(1,chars + 1) for i in random.choice('-+1234567890.')]) i = scanum(i) if i: print(i) ## uses also scientific notation ok += 1 print() print( ("Out of %i tested %i long numbers, %i were ok, (%.2f %%)" % (num, chars, ok, (float(ok)/num*100)) ))
However, sometimes it is useful practise to do things by yourself for practise or for understanding techniques. Also to this own made function could add features like thousands separator and comma used instead of decimal point.
Edited by pyTony: n/a