使用isdigit浮动?

时间:2010-11-09 20:23:30

标签: 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? ')

此功能仅在用户输入integer时有效,但我希望即使他们输入float也可以使用,但是当他们输入string时却不能。

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

我该怎么做?

8 个答案:

答案 0 :(得分:33)

EAFP

try:
    x = float(a)
except ValueError:
    print("You must enter a number")

答案 1 :(得分:11)

使用正则表达式。

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? ')

答案 2 :(得分:11)

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

但是,如果您确实想要进行验证,则可以在使用isdigit()之前删除正好1个小数点。

>>> "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

请注意,这并不会将浮点数视为与整数不同。如果你真的需要它,你可以添加那个检查。

答案 3 :(得分:6)

以dan04的答案为基础:

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

用法:

isDigit(3)     # True
isDigit(3.1)   # True
isDigit("3")   # True
isDigit("3.1") # True
isDigit("hi")  # False

答案 4 :(得分:3)

我认为@ dan04有正确的方法(EAFP),但不幸的是现实世界通常是一个特例,并且管理事物确实需要一些额外的代码 - 所以下面是更复杂,但也更务实(和现实的):

import sys

while True:
    try:
        a = raw_input('How much is 1 share in that company? ')
        x = float(a)
        # validity check(s)
        if x < 0: raise ValueError('share price must be positive')
    except ValueError, e:
        print("ValueError: '{}'".format(e))
        print("Please try entering it again...")
    except KeyboardInterrupt:
        sys.exit("\n<terminated by user>")
    except:
        exc_value = sys.exc_info()[1]
        exc_class = exc_value.__class__.__name__
        print("{} exception: '{}'".format(exc_class, exc_value))
        sys.exit("<fatal error encountered>")
    else:
        break  # no exceptions occurred, terminate loop

print("Share price entered: {}".format(x))

样本用法:

> python numeric_input.py
How much is 1 share in that company? abc
ValueError: 'could not convert string to float: abc'
Please try entering it again...
How much is 1 share in that company? -1
ValueError: 'share price must be positive'
Please try entering it again...
How much is 1 share in that company? 9
Share price entered: 9.0

> python numeric_input.py
How much is 1 share in that company? 9.2
Share price entered: 9.2

答案 5 :(得分:3)

import re

string1 = "0.5"
string2 = "0.5a"
string3 = "a0.5"
string4 = "a0.5a"

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

if p.match(string1):
    print(string1 + " float or int")
else:
    print(string1 + " not float or int")

if p.match(string2):
    print(string2 + " float or int")
else:
    print(string2 + " not float or int")

if p.match(string3):
    print(string3 + " float or int")
else:
    print(string3 + " not float or int")

if p.match(string4):
    print(string4 + " float or int")
else:
    print(string4 + " not float or int")

output:
0.5 float or int
0.5a not float or int
a0.5 not float or int
a0.5a not float or int

答案 6 :(得分:2)

s = '12.32'
if s.replace('.', '').replace('-', '').isdigit():
    print(float(s))

请注意,这也适用于否定float

答案 7 :(得分:0)

如果字符串包含某些特殊字符(例如下划线)(例如'1_1'),则提供的答案将失败。在我测试的所有情况下,以下函数均会返回正确答案。

def IfStringRepresentsFloat(s):
try:
    float(s)
    return str(float(s)) == s
except ValueError:
    return False