python 数字判断

Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not.

Valid examples, should return true:

isDigit("3")
isDigit("  3  ")
isDigit("-3.23")

should return false:

isDigit("3-4")
isDigit("  3   5")
isDigit("3 5")
isDigit("zero")

python对数字的判断可以使用 str.isdigit(),如果字符串只包含数字则返回 True 否则返回 False。

但是从上述的描述来看,还需要能识别浮点数,此时 str.isdigit()就无法满足了。此时可以使用内建的类型转换函数 float()

>>>str='-3.332'
>>>float(str)
-3.332

>>>str='s33.3'
>>>float(str)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: a3.3

很显然,还需要添加一些异常处理代码,才能使函数输出True和False。

另外isDigit("  3  ")返回True,isDigit("  3   5")和isDigit("3 5")都返回False。所以需要前后去空格。

float()函数中自动将传入的str前后去空格了

def isDigit(str):

    try: 
        f = float(str) 
    except ValueError: 
        return False
    else:
        return True
        

或者使用正则模块re

>>> import re
>>> str='+3.3'
>>> value = re.compile(r'^[-+]?\d*\.{0,1}\d+$')
>>> result=value.match(str)
>>> result
<_sre.SRE_Match object at 0x0000000004D0D510>
>>> result.group()
'+3.3'
>>>
>>> str='a3.3'
>>> result=value.match(str)
>>> result
>>>                # result为空
>>> result.group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>>

所以答案可以写为

import re
def isDigit(str):
    #11ELF
    value = re.compile(r'^[-+]?\d*\.{0,1}\d+$')
    result=value.match(str)
    if result:
        return True
    else:
        return False
    
    
    

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值