Python 将 isdigit 用于浮点数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4138202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using isdigit for floats?
提问by Peter Nolan
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.
这仅在用户输入 an 时有效integer,但我希望即使他们输入 a 也能工作float,但当他们输入 a 时不起作用string。
So the user should be able to enter both 9and 9.2, but not abc.
所以用户应该能够同时输入9和9.2,但不能输入abc。
How should I do it?
我该怎么做?
采纳答案by Peter C
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? ')
回答by dan04
EAFP
EAFP
try:
x = float(a)
except ValueError:
print("You must enter a number")
回答by martineau
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):
我认为@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))
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
回答by Cam Hymanson
The existing answers are correct in that the more Pythonic way is usually to try...except(i.e. EAFP).
现有的答案是正确的,因为更 Pythonic 的方式通常是try...except(即 EAFP)。
However, if you really want to do the validation, you could remove exactly 1 decimal point before using isdigit().
但是,如果您真的想要进行验证,则可以在使用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.
请注意,这不会将浮点数视为与整数有任何不同。如果您真的需要它,您可以添加该检查。
回答by Jigyasu Tailor
s = '12.32'
if s.replace('.', '').replace('-', '').isdigit():
print(float(s))
Note that this will work for negative floats as well.
请注意,这也适用于负数float。
回答by Phlox Midas
Building on dan04's answer:
基于 dan04 的回答:
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
回答by Yakir GIladi Edry
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

