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

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

当前回答

检查后将值转换为字符串为整数,然后检查字符串第一个字符值为-或+,其余字符串为数字。最后检查isdigit。 Test = ['1', '12015', '1..]2 ', ' a2kk78”、“1.5”,2,1.24,“-8.5”,“+”、“1”、“88751.71 + 7)

检查

for k,v in enumerate(test): 
    print(k, v, 'test: ', True if isinstance(v, int) is not False else True if str(v)[0] in ['-', '+'] and str(v)[1:].isdigit() else str(v).isdigit())

结果

0 1 test:  True
1 12015 test:  True
2 1..2 test:  False
3 a2kk78 test:  False
4 1.5 test:  False
5 2 test:  True
6 1.24 test:  False
7 -8.5 test:  False
8 +88751.71 test:  False
9 -1 test:  True
10 +7 test:  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()只编译正则表达式一次。

我认为

s.startswith('-') and s[1:].isdigit()

最好重写为:

s.replace('-', '').isdigit()

因为s[1:]也创建了一个新的字符串

但更好的解决办法是

s.lstrip('+-').isdigit()

我的建议如下:

import ast

def is_int(s):
    return isinstance(ast.literal_eval(s), int)

从文档中可以看出:

安全地计算表达式节点或包含Python文字或容器显示的字符串。提供的字符串或节点只能由以下Python文字结构组成:字符串、字节、数字、元组、列表、字典、集、布尔值和None。

我应该指出,当对任何不构成Python文字的内容调用时,这将引发ValueError异常。因为这个问题要求一个没有try/except的解决方案,我有一个Kobayashi-Maru类型的解决方案:

from ast import literal_eval
from contextlib import suppress

def is_int(s):
    with suppress(ValueError):
        return isinstance(literal_eval(s), int)
    return False

¯\_(五)_/¯

我一直这样做,我对使用try/except模式有一种温和但不可否认的非理性厌恶。我用这个:

all([xi in '1234567890' for xi in x])

它不包含负数,所以你可以去掉左边所有的负号,然后检查结果是否包含0-9之间的数字:

all([xi in '1234567890' for xi in x.lstrip('-')])

如果你不确定输入是字符串,你也可以将x传递给str():

all([xi in '1234567890' for xi in str(x).lstrip('-')])

有一些(边缘?)情况下,这是行不通的:

It doesn't work for various scientific and/or exponential notations (e.g. 1.2E3, 10^3, etc.) - both will return False. I don't think other answers accommodated this either, and even Python 3.8 has inconsistent opinions, since type(1E2) gives <class 'float'> whereas type(10^2) gives <class 'int'>. An empty string input gives True. A leading plus sign (e.g. "+7") gives False. Multiple minus signs are ignored so long as they're leading characters. This behavior is similar to the python interpreter* in that type(---1) returns <class int>. However, it isn't completely consistent with the interpreter in that int('---1') gives an error, but my solution returns True with the same input.

所以它不会对所有可能的输入都有效,但如果你能排除这些,这是一个OK的单行检查,如果x不是整数返回False,如果x是整数返回True。但是如果你真的想要精确模拟int()内置的行为,你最好使用try/except。

我不知道这是否是python式的,但它只有一行,而且代码的功能相对清晰。

我并不是说解释器忽略了前导负号,只是说任何数量的前导负号都不会改变结果是整数。Int(——1)实际上被解释为-(-1)或1。Int(——1)被解释为-(-(-1)),或者-1。所以前面有偶数个负号就会得到一个正整数,前面有奇数个负号就会得到一个负整数,但结果总是整数。

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

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

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