使用isdigit浮动?

Pet*_*lan 26 python parsing user-input

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 share in that company? ')
Run Code Online (Sandbox Code Playgroud)

这仅在用户输入时才有效integer,但我希望即使他们输入了一个,但我希望它能够工作float,而不是在他们输入时string.

因此,用户应该能够同时输入99.2,但不会abc.

我该怎么办?

dan*_*n04 36

EAFP

try:
    x = float(a)
except ValueError:
    print("You must enter a number")
Run Code Online (Sandbox Code Playgroud)

  • EAFP =比宽容更容易要求宽恕(参见http://docs.python.org/glossary.html) (11认同)

Cam*_*son 13

现有的答案是正确的,因为通常更多的Pythonic方式try...except(即EAFP).

但是,如果您确实想要进行验证,则可以在使用前删除正好1个小数点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
Run Code Online (Sandbox Code Playgroud)

请注意,这并不会处理与int不同的浮点数.如果你真的需要它,你可以添加该检查.


Pet*_*r C 12

使用正则表达式.

import re

p = re.compile('\d+(\.\d+)?')

a = raw_input('How much is 1 share in that company? ')

while p.match(a) == None:
    print "You need to write a number!\n"
    a = raw_input('How much is 1 share in that company? ')
Run Code Online (Sandbox Code Playgroud)

  • 那些正则表达式非常灵活!尽管如此,dan04的解决方案仍然感觉更加诡异.在这里,我将pythonic定义为"在两个具有相同复杂度的解决方案之间,更喜欢不使用正则表达式的解决方案".这仍然留下许多正则表达式的应用程序. (3认同)

Phl*_*das 6

以dan04的答案为基础:

def isDigit(x):
    try:
        float(x)
        return True
    except ValueError:
        return False
Run Code Online (Sandbox Code Playgroud)

用法:

isDigit(3)     # True
isDigit(3.1)   # True
isDigit("3")   # True
isDigit("3.1") # True
isDigit("hi")  # False
Run Code Online (Sandbox Code Playgroud)


小智 5

s = '12.32'
if s.replace('.', '').replace('-', '').isdigit():
    print(float(s))
Run Code Online (Sandbox Code Playgroud)

float请注意,这也适用于负数。