Using isdigit for floats?

前端 未结 8 1058
故里飘歌
故里飘歌 2020-12-05 09:59
a = raw_input(\'How much is 1 share in that company? \')

while not a.isdigit():
    print(\"You need to write a number!\\n\")
    a = raw_input(\'How much is 1 shar         


        
相关标签:
8条回答
  • 2020-12-05 10:45

    Building on dan04's answer:

    def isDigit(x):
        try:
            float(x)
            return True
        except ValueError:
            return False
    

    usage:

    isDigit(3)     # True
    isDigit(3.1)   # True
    isDigit("3")   # True
    isDigit("3.1") # True
    isDigit("hi")  # False
    
    0 讨论(0)
  • 2020-12-05 10:53

    The existing answers are correct in that the more Pythonic way is usually to try...except (i.e. EAFP).

    However, if you really want to do the validation, you could remove exactly 1 decimal point before using isdigit().

    >>> "124".replace(".", "", 1).isdigit()
    True
    >>> "12.4".replace(".", "", 1).isdigit()
    True
    >>> "12..4".replace(".", "", 1).isdigit()
    False
    >>> "192.168.1.1".replace(".", "", 1).isdigit()
    False
    

    Notice that this does not treat floats any different from ints however. You could add that check if you really need it though.

    0 讨论(0)
提交回复
热议问题