Search code examples
pythonif-statementbooleanboolean-expression

Why is python if condition not working for values of "False"?


In the following code, is_number is False for the value "foo", but this still prints is a number for that string. Why? And how do I fix it?

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")

Output:

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

Solution

  • Return a bool, not a str:

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

    Any non-empty string in Python is considered true (or "truthy"), including "False":

    >>> bool("False")
    True
    

    Then of course, the regex for your number detection is a bit off:

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

    would be a tighter test.