20 表示数值的字符串

题:实现一个函数用来判断字符串str是否表示数值(包括科学计数法的数字,小数和整数)。

  • 正则化用的非常666 
import re
 
class Solution:
    def isNumeric(self, str):
        res = re.match('^\s*[+-]{0,1}((\d)+((\.)(\d)+){0,1}|((\.)(\d)+)|((\d)+(\.)))([eE][+-]{0,1}[\d]+){0,1}\s*$',str)
        if res:
            return True
        else:
            return False
  • 主要关注哪些会使其返回false 
class Solution:
    def isNumeric(self , str: str) -> bool:
        # write code here
        s=str.strip()
        if not s:
            return False
        if s[0]=="+" or s[0]=="-":
            s=s[1:]
        count_dot=0
        count_e=0
        res=False #相当于开关
        for i in range(len(s)):
            if '0'<=s[i]<='9':
                res=True 
            elif s[i]=='.':#
                count_dot+=1
                if count_dot>1 or count_e>0:#两个小数点或者小数点在e后 直接毙掉
                    return False
            elif s[i]=="e" or s[i]=="E":
                count_e+=1
                if count_e>1 or not res:#两个e或者e的前面没有数字 直接毙掉
                    return False 
                else:
                    print(2)
                    res=False #等待着是否后续有数字出现 拨开关(保证e后有数字)
            elif s[i]=="+"or s[i]=="-":
                if s[i-1]!="e" and s[i-1]!="E":#要是有符号又不在e后 直接毙掉
                    return False
            elif s[i] not in ['+','-','e','E',' ']:#一旦有奇怪的字符 直接毙掉
                return False
        return res

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值