Skip to main content
 首页 » 编程设计

python之验证 Python 字符串中的整数

2025年05月04日21shangdawei

我们有大量的字符串,其中包含可能是整数的子字符串,例如。

mystring = "123 345 456 567 678 789" 

并且需要验证:

一个。每个子字符串实际上是一个整数,例如。在 mystring = "123 345 456 567 abc 789" 到达 'abc' 时失败

每个整数都在 0 <= i <= 10000 范围内,例如。 mystring = "123 -345 456 567 678 789" 到达 '-345' 时失败

一种解决方案是:

mylist= [int(i) for i in mystring.split() if isinstance(int(i), int) and (0 <= int(i) <= 10000)] 

问题是:

我。在列表推导中,对于每个 i,int(i) 是否被评估一次或多次?

二。有没有更快的替代方法(因为字符串的体积很大,每个字符串可能包含数百到数千个整数)?

请您参考如下方法:

我想我可能会使用类似的东西:

try: 
    if not all( (0 <= int(i) <= 10000) for i in mystring.split() ): 
       raise ValueError("arg!") 
except ValueError: 
    print "Oops, didn't pass" 

这样做的好处是,如果某些东西无法转换为 int 或者它不在正确的范围内,它就会短路。

这是一个愚蠢的测试:

def test_str(mystring): 
    try: 
        return all( (0 <= int(i) <= 10000) for i in mystring.split() ) 
    except ValueError: 
        return False 
 
print test_str("123 345 456 567 abc 789") 
print test_str("123 345 456 567 -300 789") 
print test_str("123 345 456 567 300 789")