题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
自己实现
class Solution: # s字符串 def isNumeric(self, s): # write code here AllList = ['-','+','e','E','.','0','1','2','3','4','5','6','7','8','9'] flag = 0 for i in range(0,len(s)): if s[i] in AllList: if (s[i]=='+' or s[i]=='-') and (i==0 or s[i-1]=='E' or s[i-1]=='e'): continue elif s[i]=='E' or s[i]=='e' and i!=0 and s[i-1] in AllList[6:] and i!=len(s)-1: flag = 1 continue elif s[i]=='.' and flag == 0 and i!=len(s)-1 and s[i+1] in AllList[5:]: flag = 1 continue elif s[i] in AllList[5:]: continue else: return False else: return False return True
讨论区代码:
#利用python中的正则模块进行匹配
# -*- coding:utf-8 -*- class Solution: # s字符串 def isNumeric(self, s): import re p=re.compile(r'^[+-]?d*(.d+)?([eE][+-]?d+)?$') return p.match(s)