有没有办法告诉一个字符串是否代表一个整数(例如,'3','-17'但不是'3.14'或'asfasfas')而不使用try/except机制?

is_int('3.14') == False
is_int('-7')   == True

当前回答

可以用下面的方法进行检查。

def check_if_string_is_int(string1):
    for character in string1:
        if not character.isdigit():
            return "Not a number"
    else:
        return "Is a number"

其他回答

呃. .试试这个:

def int_check(a):
    if int(a) == a:
        return True
    else:
        return False

如果你不输入非数字的字符串,这是可行的。

还有(我忘了写数字检查部分了。),有一个函数检查字符串是否是数字。它是str.isdigit()。这里有一个例子:

a = 2
a.isdigit()

如果调用a.s isdigit(),它将返回True。

如果你真的不喜欢到处使用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认为是整数的所有字符串。要我说,你就用蟒语吧。

我有一种可能根本不使用int,除非字符串不代表数字,否则不应该引发异常

float(number)==float(number)//1

它应该适用于任何类型的字符串,float接受,正,负,工程符号…

如果你想只接受低ascii码的数字,这里有这样做的测试:

Python 3.7+:(u.isdecimal() and u.isascii()))

Python <= 3.6:(u.isdecimal() and u == str(int(u)))

其他答案建议使用.isdigit()或.isdecimal(),但它们都包含一些上unicode字符,如'缌' (u'\u0662'):

u = u'\u0662'     # '٢'
u.isdigit()       # True
u.isdecimal()     # True
u.isascii()       # False (Python 3.7+ only)
u == str(int(u))  # False

Greg Hewgill的方法缺少了几个组件:前导的“^”只匹配字符串的开头,并且预先编译re。但是这种方法可以让你避免尝试:

import re
INT_RE = re.compile(r"^[-]?\d+$")
def RepresentsInt(s):
    return INT_RE.match(str(s)) is not None

我很感兴趣为什么你试图避免尝试:除了?