![](/img/trans.png)
[英]Python determine whether variable is number when can be string or int?
[英]How to determine whether string is a number when the number is negative
我得到以下结果:
>>> x = '-15'
>>> print x.isdigit()
False
当我期望它是True
。 似乎没有内置函数为负数字符串返回True
。 检测它的建议是什么?
推荐的方法是try
:
try:
x = int(x)
except ValueError:
print "{} is not an integer".format(x)
如果您还期望十进制数,请使用float()
而不是int()
。
可能有一种更优雅的Python方式,但一般方法是检查第一个字符是否为'-'
,如果是,则在第二个字符之后调用isdigit
。
也许正则表达式是一个开销,但这可能会在数字之前捕获+
和-
并且也可以捕获float
和int
:
(基于@Mark的评论)
码:
import re
def isdigit(string):
return bool(re.match(r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)', string))
DEMO:
print isdigit('12') # True
print isdigit('-12') # True
print isdigit('aa') # False
print isdigit('1a2a') # False
print isdigit('-12-12') # False
print isdigit('-12.001') # True
print isdigit('+12.001') # True
print isdigit('.001') # True
print isdigit('+.001') # True
print isdigit('-.001') # True
print isdigit('-.') # False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.