使用 isdigit 表示浮点数?

问题描述 投票:0回答:9
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
时则不起作用。

因此用户应该能够输入

9
9.2
,但不能输入
abc

我该怎么做?

python parsing user-input
9个回答
45
投票

EAFP

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

37
投票

现有的答案是正确的,因为更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

请注意,这对浮点数的处理与整数没有任何不同。如果您确实需要的话,您可以添加该检查。


17
投票

使用正则表达式。

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

12
投票

以 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

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

请注意,这也适用于负

float


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

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

1
投票

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

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

0
投票

`a = raw_input('那家公司 1 股多少钱?')

虽然不是 a.isdigit() 或 a.isdecimal(): print("你需要写一个数字! ”) a = raw_input('那家公司 1 股多少钱?')`

© www.soinside.com 2019 - 2024. All rights reserved.