表示数值的字符串python

讨论区看到的答案,太妙了,值得收藏

class Solution:
    # s字符串
    def isNumeric(self, s):
        sign,decimal,hasE = False,False,False
        for i in range(0,len(s)):
            if s[i] in ['e','E']:
                if i == len(s)-1 or hasE:
                    return False
                hasE = True
            elif s[i] == '.':
                if hasE or decimal:
                    return False
                decimal = True
            elif s[i] in ['+','-']:
                if not sign and i>0 and s[i-1] not in ['e','E']:
                    return False
                if sign and s[i-1] not in ['e','E']:
                    return False
            else:
                if s[i]<'0' or s[i]>'9':
                    return False
        return True

你可能感兴趣的:(剑指offer)