使用 isdigit 表示浮点数?

发布于 2024-10-01 02:09:30 字数 397 浏览 10 评论 0原文

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

仅当用户输入整数时才有效,但我希望即使他们输入浮点也能工作,但当他们输入字符串时则不起作用>。

因此,用户应该能够输入 99.2,但不能输入 abc

我该怎么做呢?

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

This only works if the user enters an integer, but I want it to work even if they enter a float, but not when they enter a string.

So the user should be able to enter both 9 and 9.2, but not abc.

How should I do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

往日情怀 2024-10-08 02:09:30

EAFP

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

EAFP

try:
    x = float(a)
except ValueError:
    print("You must enter a number")
缪败 2024-10-08 02:09:30

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

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

The existing answers are correct in that the more Pythonic way is usually to try...except (i.e. EAFP, "easier to ask for forgiveness than permission").

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.

饮湿 2024-10-08 02:09:30

使用正则表达式。

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

Use regular expressions.

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? ')
傻比既视感 2024-10-08 02:09:30

基于 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

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
我最亲爱的 2024-10-08 02:09:30
s = '12.32'
if s.replace('.', '').replace('-', '').isdigit():
    print(float(s))

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

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

Note that this will work for negative floats as well.

昔梦 2024-10-08 02:09:30

我认为@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

I think @dan04 has the right approach (EAFP), but unfortunately the real world is often a special case and some additional code is really required to manage things—so below is a more elaborate, but also a bit more pragmatic (and realistic):

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

Sample usage:

> 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
烟─花易冷 2024-10-08 02:09:30
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
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
若无相欠,怎会相见 2024-10-08 02:09:30

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

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

The provided answers fail if the string contains some special characters such as underscore (e.g. '1_1'). The following function returns correct answer in all case that I tested.

def IfStringRepresentsFloat(s):
try:
    float(s)
    return str(float(s)) == s
except ValueError:
    return False
梦亿 2024-10-08 02:09:30
a = raw_input('How much is 1 share in that company? ')

while not a.isdigit() or a.isdecimal():
    print("You need to write a number!\n")
    a = raw_input('How much is 1 share in that company? ')
a = raw_input('How much is 1 share in that company? ')

while not a.isdigit() or a.isdecimal():
    print("You need to write a number!\n")
    a = raw_input('How much is 1 share in that company? ')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文