number = self.getNumber(string/number .. to test)
# test if a val contains a valid number, if not return ""
# return the number if any meaningful number (with letters before and after return that number)
# u"the values is -123.5 Amps" returns -123.5
# -1.3e5 returns -130000.0
# -1.3e-5 returns -0.000013
# u"1.3e-5" returns -0.000013
# u"1.3e-5x" returns "" ( - sign not first position ..need to include)
# True, u"truE" u"on" "ON".. returns 1.0; False u"faLse" u"off" returns 0.0
# u"1 2 3" returns ""
# u"1.2.3" returns ""
# u"12-5" returns ""
- Code: Select all
def getNumber(self,val):
x = ""
try:
x = float(val)
return x
except:
pass
try:
xx = ''.join([c for c in val if c in '-1234567890.']) # remove non numbers
lenXX= len(xx)
if lenXX > 0: # found numbers..
if len( ''.join([c for c in xx if c in '.']) ) >1: return "" # remove strings that have 2 or more dots " 5.5 6.6"
if len( ''.join([c for c in xx if c in '-']) ) >1: return "" # remove strings that have 2 or more - " 5-5 6-6"
if len( ''.join([c for c in xx if c in '1234567890']) ) ==0: return "" # remove strings that just no numbers, just . amd - eg "abc.xyz- hij"
if lenXX ==1 : return float(xx) # just one number
if xx.find("-") > 0 : return "" # reject if "-" is not in first position
valList = list(val) # make it a list
count = 0 # count number of numbers
for i in range(len(val)-1): # reject -0 1 2.3 4 not consecutive numbers:..
if (len(''.join([c for c in valList[i] if c in '-1234567890.'])) ==1 ): # check if this character is a number, if yes:
count +=1 #
if count >= lenXX : break # end of # of numbers, end of test: break, its a number
if (len(''.join([c for c in valList[i+1] if c in '-1234567890.'])) )== 0: return "" # next is not a number and not all numbers accounted for, so it is numberXnumber
return float(xx) # must be a real number, everything else is excluded
else: # only text left, no number in this string
val = str(val).upper() # if unicode return "" (-->except:)
if val== "TRUE" or val =="ON" : return 1.0 # true/on --> 1
if val== "FALSE" or val =="OFF" : return 0.0 # false/off --> 0
return "" # all tests failed ... nothing there, return "
except:
return "" # something failed eg unicode only ==> return ""
return "" # should not happen just for safety
copied into an editor the formatting is better..
Karl