有没有办法告诉一个字符串是否代表一个整数(例如,'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
当前回答
我有一种可能根本不使用int,除非字符串不代表数字,否则不应该引发异常
float(number)==float(number)//1
它应该适用于任何类型的字符串,float接受,正,负,工程符号…
其他回答
我有一种可能根本不使用int,除非字符串不代表数字,否则不应该引发异常
float(number)==float(number)//1
它应该适用于任何类型的字符串,float接受,正,负,工程符号…
呃. .试试这个:
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有一个时间惩罚:
测试数据
首先,我创建了一个包含200个字符串、100个失败字符串和100个数字字符串的列表。
from random import shuffle
numbers = [u'+1'] * 100
nonumbers = [u'1abc'] * 100
testlist = numbers + nonumbers
shuffle(testlist)
testlist = np.array(testlist)
numpy解决方案(仅适用于数组和unicode)
Np.core.defchararray.isnumeric也可以用于unicode字符串,但它返回一个数组。所以,如果你必须做成千上万的转换,并且有丢失的数据或非数值数据,这是一个很好的解决方案。
import numpy as np
%timeit np.core.defchararray.isnumeric(testlist)
10000 loops, best of 3: 27.9 µs per loop # 200 numbers per loop
试/除了
def check_num(s):
try:
int(s)
return True
except:
return False
def check_list(l):
return [check_num(e) for e in l]
%timeit check_list(testlist)
1000 loops, best of 3: 217 µs per loop # 200 numbers per loop
numpy解决方案似乎更快。
我用的最简单的方法
def is_int(item: str) -> bool:
return item.lstrip('-+').isdigit()
我认为
s.startswith('-') and s[1:].isdigit()
最好重写为:
s.replace('-', '').isdigit()
因为s[1:]也创建了一个新的字符串
但更好的解决办法是
s.lstrip('+-').isdigit()