Max
Max

Reputation: 1487

Python: any() statement not returning true as expected

I have to check if multiple strings are in one line. The first any statement returns true as expected, but the second one returns false and I have no idea why, maybe its a really stupid mistake...

lines[-10] = 'Step   0:     3'
lines[-1]  = 'Step   9:    30'

What I am doing:

with open('stdout.txt', 'r') as f:
    lines = f.readlines()

print(inputs)
if set(inputs) == set(['10', '3', '+']):
    if any(x in ['0:', '3'] for x in lines[-10]):
        print('ok')
        test = True
    else:
        print('error')
        test = False


    print(lines[-1])
    #if '30' in lines[-1] and '9:' in lines[-1]: returns true !!!
    if any(x in ['9:', '30'] for x in lines[-1]):
        print('ok')
        test = test & True
    else:
        print('error')
        test = test & False

As you can see in the sample, if I check each value by it self it works.

Upvotes: 0

Views: 87

Answers (4)

scriptboy
scriptboy

Reputation: 856

If you supply a minimum case here, I think you can figure out by your self.

In [3]: any(x in ['9:', '30'] for x in line[-1])
Out[3]: False

In [4]: any(x in ['9:', '30'] for x in line)
Out[4]: False

In [5]: line = 'Step   9:    30'

In [6]: any(x in ['9:', '30'] for x in line)
Out[6]: False

In [7]: for x in line:
   ...:     print(x)
   ...:
S
t
e
p



9
:




3
0

In [8]: x = "9"

In [9]: x in ['9:', '30']
Out[9]: False

In [10]: x in '9:3-'
Out[10]: True

So, for string, if you iterate it, you will get char, and for a list of items(like ['9:', '30']), you will get items('9:', '30').

You can try it in Python console.

Upvotes: 0

BartDur
BartDur

Reputation: 1106

As explained in other answers x for x in 'string' yields individual characters which can never be identical to e.g. '9:' or '30', the first any() works because you compare x to '3'. Instead you could do:

if any(x in lines[-1] for x in ['9:','30']):
    do_stuff...

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

x for x in "somestring" will yield each individual character of somestring:

for x in 'Step   9:    30':
    print("x is '{}'.format(x))

Now obviously, since ['9:', '30'] is a list of two-characters strings, none of the single individual characters of 'Step 9: 30' are element of it.

Upvotes: 2

quamrana
quamrana

Reputation: 39394

Maybe you mean this:

if any((term in lines[-10]) for term in ['0:', '3']):
# etc

#if '30' in lines[-1] and '9:' in lines[-1]: returns true !!!
if any((term in lines[-10]) for term in ['9:', '30']):

Upvotes: 2

Related Questions