Search code examples
pythonloopssplitline

Iterating through all lines with multiple conditions


I want to iterate over all lines at once and check if the string is in any of the lines, if it is then apply a function and break out of the loop, if not then check for the second string and do the same thing. If neither string if found in any of the lines then carry on with the else..

split= text.as_string().splitlines()
for row in split:
   if 'Thanks Friend' in row.any():
     apply_some_function()
     break
   elif 'other text' in row.str.any():
     apply_some_function()
     break
   else:
     .......

I keep getting the error:


AttributeError                            Traceback (most recent call last)
      <ipython-input-179-8f0e09f62771> in <module>()
      1 for row in split:
      2 
----> 3   if 'Thanks Friend' in row.str.any():
      4     apply_some_function()
      5     break

AttributeError: 'str' object has no attribute 'str'

Solution

  • Try the following. But keep in mind that the text will be split at the carriage return which might not be what you want to do. Also, do you want to do something different if 'other text' is in split? If you do then you need to tell us.

    split = text.split("\n")
    if any(x for x in split if 'Thanks Friend' in x):
        apply_some_function()
    elif any(x for x in split if 'other text' in x):
        apply_some_function()
    else:
        pass
    

    You can also do:

    if any(x for x in split if 'Thanks Friend' in x) or \:
    any(x for x in split if 'other text' in x):
        apply_some_function()