Python 使用isdigit进行浮动?

Python 使用isdigit进行浮动?,python,parsing,user-input,Python,Parsing,User Input,这仅在用户输入整数时起作用,但我希望即使他们输入浮点,它也能起作用,但在他们输入字符串时不起作用 因此,用户应该能够同时输入9和9.2,但不能输入abc 我该怎么做?EAFP 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 i

这仅在用户输入
整数
时起作用,但我希望即使他们输入
浮点
,它也能起作用,但在他们输入
字符串
时不起作用

因此,用户应该能够同时输入
9
9.2
,但不能输入
abc

我该怎么做?

EAFP

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

使用正则表达式

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

我认为@dan04的方法是正确的(EAFP),但不幸的是,现实世界通常是一个特例,需要一些额外的代码来管理事情,因此下面的代码更详细,但也更实用(和现实):


现有的答案是正确的,因为更具python风格的方式通常是
尝试…除了
(即EAFP)

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

请注意,这并不处理与int有任何不同的浮动。如果你真的需要的话,你可以加上那张支票

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

请注意,这也适用于负浮动。

基于dan04的答案:

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

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

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

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

EAFP=请求原谅比请求许可更容易(请参见)@Steven Rumbaski,尽管我更喜欢这种形式:“请求原谅比请求许可更容易”:-)好的,那么有没有一种简单的方法来检查用户是否输入了负值?我也尝试过使用它,但它只起作用一次,如果你不止一次尝试输入一个字母或str,你仍然会得到一个错误。那些正则表达式太灵活了!尽管如此,dan04的解决方案还是让人觉得更像蟒蛇。在这里,我将pythonic定义为“在两个同等复杂度的解决方案之间,选择不使用正则表达式的解决方案。”这仍然让许多应用程序使用正则表达式。@史蒂文·伦巴尔斯基:是的,dan04的解决方案似乎更具pythonic,我认为我的可能实际上是更少的代码。不幸的是,这不是一个好的浮动正则表达式,因此不能真正回答这个问题。例如,它与“.1”不匹配,但与“5abc”匹配。还有负值和其他符号,因此使用dan04的答案可能是理想的,如果需要在列表理解或参数中使用它,可以将其转换为函数。@Looney:我大约3年前写过这个。我肯定认为dan04的答案现在好多了。但是,只需将正则表达式更改为/^\d+(\.\d+)?$/就可以了。我不认为匹配.1是必要的,他不想匹配负数。我更喜欢这个解决方案,而不是上面的其他3。这里的问题是,如果你提供布尔值或无。对于布尔型,如果没有异常,则为真。对于在“float(x)”上失败且没有“ValueError”的任何其他数据类型
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
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
def IfStringRepresentsFloat(s):
try:
    float(s)
    return str(float(s)) == s
except ValueError:
    return False