有没有办法告诉一个字符串是否代表一个整数(例如,'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
当前回答
我认为
s.startswith('-') and s[1:].isdigit()
最好重写为:
s.replace('-', '').isdigit()
因为s[1:]也创建了一个新的字符串
但更好的解决办法是
s.lstrip('+-').isdigit()
其他回答
如果你想只接受低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
Str.isdigit()应该可以做到这一点。
例子:
str.isdigit("23") ## True
str.isdigit("abc") ## False
str.isdigit("23.4") ## False
编辑: 正如@BuzzMoschetti指出的那样,这种方法对于负数(例如“-23”)将失败。如果您的input_num可以小于0,请在应用str.isdigit()之前使用re.sub(regex_search,regex_replace,contents)。例如:
import re
input_num = "-23"
input_num = re.sub("^-", "", input_num) ## "^" indicates to remove the first "-" only
str.isdigit(input_num) ## True
我一直这样做,我对使用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。所以前面有偶数个负号就会得到一个正整数,前面有奇数个负号就会得到一个负整数,但结果总是整数。
>>> "+7".lstrip("-+").isdigit()
True
>>> "-7".lstrip("-+").isdigit()
True
>>> "7".lstrip("-+").isdigit()
True
>>> "13.4".lstrip("-+").isdigit()
False
所以你的函数是
def is_int(val):
return val.lstrip("-+").isdigit()
如果你真的不喜欢到处使用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认为是整数的所有字符串。要我说,你就用蟒语吧。