有没有办法告诉一个字符串是否代表一个整数(例如,'3','-17'但不是'3.14'或'asfasfas')而不使用try/except机制?
is_int('3.14') == False
is_int('-7') == True
有没有办法告诉一个字符串是否代表一个整数(例如,'3','-17'但不是'3.14'或'asfasfas')而不使用try/except机制?
is_int('3.14') == False
is_int('-7') == True
当前回答
Greg Hewgill的方法缺少了几个组件:前导的“^”只匹配字符串的开头,并且预先编译re。但是这种方法可以让你避免尝试:
import re
INT_RE = re.compile(r"^[-]?\d+$")
def RepresentsInt(s):
return INT_RE.match(str(s)) is not None
我很感兴趣为什么你试图避免尝试:除了?
其他回答
如果你真的不喜欢到处使用try/except,请写一个helper函数:
def represents_int(s):
try:
int(s)
except ValueError:
return False
else:
return True
>>> print(represents_int("+123"))
True
>>> print(represents_int("10.0"))
False
它将需要更多的代码来精确覆盖Python认为是整数的所有字符串。要我说,你就用蟒语吧。
在我看来,这可能是最直接和python化的方法。我没有看到这个解它基本上和正则表达式的解是一样的,但是没有正则表达式。
def is_int(test):
import string
return not (set(test) - set(string.digits))
Greg Hewgill的方法缺少了几个组件:前导的“^”只匹配字符串的开头,并且预先编译re。但是这种方法可以让你避免尝试:
import re
INT_RE = re.compile(r"^[-]?\d+$")
def RepresentsInt(s):
return INT_RE.match(str(s)) is not None
我很感兴趣为什么你试图避免尝试:除了?
呃. .试试这个:
def int_check(a):
if int(a) == a:
return True
else:
return False
如果你不输入非数字的字符串,这是可行的。
还有(我忘了写数字检查部分了。),有一个函数检查字符串是否是数字。它是str.isdigit()。这里有一个例子:
a = 2
a.isdigit()
如果调用a.s isdigit(),它将返回True。
使用正则表达式:
import re
def RepresentsInt(s):
return re.match(r"[-+]?\d+$", s) is not None
如果你必须接受小数也:
def RepresentsInt(s):
return re.match(r"[-+]?\d+(\.0*)?$", s) is not None
如果经常这样做,为了提高性能,请使用re.compile()只编译正则表达式一次。