首页 > 解决方案 > 如果条件不适用于“False”值,为什么python?

问题描述

在下面的代码中,valueis_numberFalse"foo",但仍会is a number为该字符串打印。为什么?我该如何解决?

def string_is_number(a_string):
    pattern = re.compile(r'[0-9]+')
    if pattern.search(a_string):
        return("True")
    else:
        return("False")
 
for value in 42, 0.5, "foo":
    the_string = str(value)
    is_number = string_is_number(the_string)
    print(the_string, is_number)
    if is_number:
        print(the_string, "is a number")

输出:

42 True
42 is a number
0.5 True
0.5 is a number
foo False
foo is a number

标签: pythonif-statementbooleanboolean-expression

解决方案


返回 a bool,而不是 a str

if pattern.search(a_string):
    return True
else:
    return False 

Python 中的任何非空字符串都被认为是真的(或“真”),包括"False"

>>> bool("False")
True

然后,当然,您的号码检测的正则表达式有点偏离:

re.match("^\d+([.,]\d+)?$", a_string)

将是一个更严格的测试。


推荐阅读