lundi 21 décembre 2020

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

In the following code, is_number is False for the value in the first column and first row ("Project Management and Other Matters "), but this still prints "is a number" for that string. Why? And how do I fix it?

for index, row in rows_found.iterrows():
    for col in rows_found:
        the_string = str(row[col])
        is_number = string_is_number(the_string)
        print(the_string, is_number)
        if is_number:
            print(the_string, "is a number")

Actual Output:

Project Management and Other Matters  False
Project Management and Other Matters  is a number
0.5 True
0.5 is a number
12.8 True
12.8 is a number
11.8 True
11.8 is a number
25.1 True
25.1 is a number
6,381  True
6,381  is a number
Project Management and Other Matters  False
Project Management and Other Matters  is a number
0.5 True
0.5 is a number

Expected output:

Project Management and Other Matters  False
0.5 True
0.5 is a number
12.8 True
12.8 is a number
11.8 True
11.8 is a number
25.1 True
25.1 is a number 
6,381  True 
6,381  is a number 
Project Management and Other Matters  False
0.5 True
0.5 is a number

The code for the string_is_number function:

def string_is_number(a_string):
    
    pattern = re.compile(r'[0-9]+')
    
    if pattern.search(a_string):
        return("True")
    else:
        return("False")

Aucun commentaire:

Enregistrer un commentaire