Home > Back-end >  Cant use the Boolean operator 'or' in a if statement to initiate if either string contains
Cant use the Boolean operator 'or' in a if statement to initiate if either string contains

Time:06-21

Part of the project I`m working on requires me to automate arcGIS functions using python. While trying to locate files I noticed that when I included the 'or' operator in my if statement that the loop would stop collecting files after currentDirList no longer contained the first string. The other half of the data is named differently and I thought I could use the 'or' operator to search for either possible naming convention. However I can only get it to work as two separate statements. This is does what I need it to do. However, I have no experience in python aside from this and I am learning as I go. Despite my attempts to search for an answer I don't understand why it doesn't work. Could someone help me understand why this is happening?

Using the 'or' operator

while listCount < listSize:
    if currentDirList[listCount].__contains__('Ashland Wheat HessianFly' or 'HF_Ashland'):
        tifPath = str(Path(dataSource   "\\"   currentDirList[listCount]))
        currentSource.append(glob.glob(tifPath   '/*.tif'))
    listCount  = 1

As separate statements

while listCount < listSize:
    if currentDirList[listCount].__contains__('Ashland Wheat HessianFly'):
        tifPath = str(Path(dataSource   "\\"   currentDirList[listCount]))
        currentSource.append(glob.glob(tifPath   '/*.tif'))
    listCount  = 1

listCount = 0
while listCount < listSize:
    if currentDirList[listCount].__contains__('HF_Ashland'):
        tifPath = str(Path(dataSource   "\\"   currentDirList[listCount]))
        currentSource.append(glob.glob(tifPath   '/*.tif'))
    listCount  = 1

CodePudding user response:

Don't call __contains__ directly, use the in operator.

You need to write two separate comparisons and combine them with or.

if 'Ashland Wheat HessianFly' in currentDirList[listCount] or 'HF_Ashland' in currentDirList[listCount]:
  • Related