Home > Software design >  Check if substring exists in a list containing booleans?
Check if substring exists in a list containing booleans?

Time:12-07

I want to check if a substring exists in a list. But i can't iterate through it because of it having booleans. I'm trying to convert booleans to str(booleans) but is that necessary? I'm sure there must be another efficient way without changing data error

def replace_falseTrue_as_strings(lst):
    for i in lst:
        if isinstance(i,list):
            for j in i:
                if all(not isinstance(j,list)):
                    for k in j:
                        k_new.append(str(k))
                    return k
                if any(isinstance(j,list)):
                    return replace_falseTrue_as_strings(j)
        else:
            i_new.append(str(i))
            return j_new

CodePudding user response:

You could add a typecheck:

any( (isinstance(x, str) and 'abl' in x) for x in some_list)

in case of x not being a string (a boolean here), isinstance(x, str) is False and the second member is not checked, this avoids the TypeError.

CodePudding user response:

Try this :

any('abl' in x for x in your_list if isinstance(x, str))

It checks the type of each item of your list and proceeds only if it's a string.

  • Related