Home > Mobile >  If statement on for-loop on strings not working despite meeting condition
If statement on for-loop on strings not working despite meeting condition

Time:06-09

I have a for loop on a list as I have shown with f below and I have a conditional statement where the first object of the list does not meet but the second and third object does. For some reason, the condition is not returning the desired result and I cannot understand why this is the case?

minimum working example

# containers
absolute_path_list = []
f = [ 'Documents/projects/packout_model/.venv/lib/python3.9/site-packages/numpy/core/tests/data/file1.csv',
 'Documents/projects/packout_model/data/03-06-2022/csv_store/file2.csv',
 '/Documents/projects/packout_model/data/03-06-2022/csv_store/file3.csv']

# loop over f to find files that meet our condition 
for file in f:
    if (file.find('csv_store') and file.find('03-06-2022')) and (file.find('packout_model') and file.endswith("csv")): # error here 
        absolute_path_list.append(file)

print(absolute_path_list) # print list of str objects that met condition

output being generated

[ 'Documents/projects/packout_model/.venv/lib/python3.9/site-packages/numpy/core/tests/data/file1.csv',
 'Documents/projects/packout_model/data/03-06-2022/csv_store/file2.csv',
 '/Documents/projects/packout_model/data/03-06-2022/csv_store/file3.csv']

desired output

['Documents/projects/packout_model/data/03-06-2022/csv_store/file2.csv',
 '/Documents/projects/packout_model/data/03-06-2022/csv_store/file3.csv']

Edit:

solution to work around on answer

Using the answer provided I managed to write a workaround. Hope it helps.

def check_found(val: str=None, substring: str=None):
    return not val.find(substring) == -1 # .find returns -1 if not found

for file in f:
    print(check_found(file, 'csv_store'))

# result

False
True
True

CodePudding user response:

In Python, bool(-1) evaluates to True. The documentation of the str.find method says if the string is not found, then it returns -1

Hence, no matter if you find or not the needles you are looking for, your condition will always evaluates to True.

You may consider testing positivity of the result, or using the similar index method that raises an exception on failure.

  • Related