题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
偷工减料法
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
try:
float(s)
return True
except:
return False
参考其他大神做法,一个一个做规则比对
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
sign = False
decimal_ = False
hasE = False
for i in range(len(s)):
if s[i] == 'e' or s[i] == 'E':
if i == len(s)-1:
return False
if hasE == True:
return False
hasE = True
elif s[i] == '+' or s[i] == '-':
if sign and s[i-1] != 'e' and s[i-1] !='E':
return False
if sign == False and i > 0 and s[i-1] != 'e' and s[i-1] !='E':
return False
sign = True
elif s[i] == '.':
if decimal_ or hasE:
return False
decimal_ = True
else:
if s[i] > '9' or s[i] < '0':
return False
return True